Created
August 17, 2017 18:13
-
-
Save cletusw/4c94b3772fb51047506377eef13671be to your computer and use it in GitHub Desktop.
Converts underscore/lodash `.each()` with context to use Function.prototype.bind()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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