Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removes pointless returns from specified methods #171

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
_.each(foo, (element, index) => {
if (index === 0) {
return;
}
return element.position = index;
});

_.filter(foo, (element, index) => {
if (index === 0) {
return;
}
return element.position = index;
});

_.doNotRemove(foo, (element, index) => {
if (index === 0) {
return;
}
return element.position = index;
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
_.each(foo, (element, index) => {
if (index === 0) {
return;
}
element.position = index;
});

_.filter(foo, (element, index) => {
if (index === 0) {
return;
}
element.position = index;
});

_.doNotRemove(foo, (element, index) => {
if (index === 0) {
return;
}
return element.position = index;
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import 'test-helper';
import removePointlessReturnsFromMethods from 'remove-pointless-returns-from-methods';

describe('removePointlessReturnsFromMethods', () => {
it('removes pointless returns from lodash methods only', () => {
expect(removePointlessReturnsFromMethods).to.transform('remove-pointless-returns-from-methods/lodash');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export default function removePointlessReturnsFromMethods({source}, {jscodeshift: j}, {printOptions = {}}) {
const sourceAST = j(source);
const POINTLESS_RETURN_METHODS = {
_: new Set(['each', 'filter']),
};
sourceAST
.find(j.CallExpression)
.filter(({node: {callee}}) => POINTLESS_RETURN_METHODS[callee.object.name].has(callee.property.name))
.forEach((nodePath) => {
const body = nodePath.node.arguments.filter((arg) => j.Function.check(arg))[0].body.body;
const returnLine = body.pop();
body.push(j.expressionStatement(returnLine.argument));
});

return sourceAST
.toSource(printOptions);
}