Skip to content

Instantly share code, notes, and snippets.

@cletusw
Last active August 17, 2017 18:08
Show Gist options
  • Save cletusw/02d8fc06c238da645522074ce271dffd to your computer and use it in GitHub Desktop.
Save cletusw/02d8fc06c238da645522074ce271dffd to your computer and use it in GitHub Desktop.
Converts underscore/lodash `.each()` with `this` context to use arrow functions.
/**
* Converts underscore/lodash `.each()` with `this` context to use arrow functions.
*
* Run this with jscodeshift
* Live demo: https://astexplorer.net/#/gist/0a47495d69719449d2afbb0f0c50f8ea/latest
*
* Converts:
* _.each(array, function(item) {
* // ...
* }, this);
*
* to:
* _.each(array, item => {
* // ...
* });
*/
module.exports = function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.CallExpression)
.filter(
path =>
path.node.callee.type === "MemberExpression" &&
path.node.callee.object.type === "Identifier" &&
path.node.callee.object.name === "_" &&
path.node.callee.property.type === "Identifier" &&
path.node.callee.property.name === "each" &&
path.node.arguments.length === 3 &&
path.node.arguments[1].type === "FunctionExpression" &&
path.node.arguments[2].type === "ThisExpression"
)
.forEach(path => {
let iterator = path.node.arguments[1];
path.node.arguments[1] = j.arrowFunctionExpression(iterator.params, iterator.body, iterator.expression);
path.node.arguments.length = 2;
})
.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment