Skip to content

Instantly share code, notes, and snippets.

@cletusw
Created August 17, 2017 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cletusw/4c94b3772fb51047506377eef13671be to your computer and use it in GitHub Desktop.
Save cletusw/4c94b3772fb51047506377eef13671be to your computer and use it in GitHub Desktop.
Converts underscore/lodash `.each()` with context to use Function.prototype.bind()
/**
* Converts underscore/lodash `.each()` with context to use Function.prototype.bind()
*
* Run this with jscodeshift
* Live demo: https://astexplorer.net/#/gist/b4294e95ef898af1d19cd3db19f9e8b0/latest
*
* Converts:
* _.each(array, function(item) {
* // ...
* }, context);
*
* to:
* _.each(array, function(item) {
* // ...
* }.bind(context));
*/
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] &&
path.node.arguments[2]
)
.forEach(path => {
let iterator = path.node.arguments[1];
let context = path.node.arguments[2];
path.node.arguments.length = 2;
path.node.arguments[1] = j.callExpression(
j.memberExpression(iterator, j.identifier("bind")),
[context]
);
})
.toSource();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment