Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.