Created
May 5, 2015 03:02
-
-
Save sparty02/a73b4e9eeca1f633da38 to your computer and use it in GitHub Desktop.
babel-plugin-foreach
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
function forEachTransform (babel) { | |
var t = babel.types; | |
return new babel.Transformer('plugin-foreach', { | |
CallExpression: function (node, parent) { | |
var callee = node.callee; | |
if (callee.property.name === 'forEach') { | |
var arrayName = callee.object.name; | |
var forEachCallback = node.arguments[0]; | |
var currentValueName = forEachCallback.params[0].name; | |
var init = t.variableDeclaration('var', [ | |
t.variableDeclarator( | |
t.identifier('i'), | |
t.literal(0) | |
) | |
]); | |
var test = t.binaryExpression( | |
'<', | |
t.identifier('i'), | |
t.memberExpression( | |
t.identifier(arrayName), | |
t.identifier('length') | |
) | |
); | |
var update = t.updateExpression('++', | |
t.identifier('i'), | |
false | |
); | |
var body = forEachCallback.body; | |
var forStatement = t.forStatement(init, test, update, body); | |
console.log('statement', forStatement); | |
return forStatement; | |
} | |
} | |
}); | |
} | |
module.exports = forEachTransform; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment