Skip to content

Instantly share code, notes, and snippets.

@Tsugami
Last active December 29, 2021 02:31
Show Gist options
  • Save Tsugami/9eabb3f200875dc89705e3618431ab05 to your computer and use it in GitHub Desktop.
Save Tsugami/9eabb3f200875dc89705e3618431ab05 to your computer and use it in GitHub Desktop.
codemod to replace Array.each to for-in in javascript
/**
* Paste or drop some JavaScript here and explore
* the syntax tree created by chosen parser.
* You can use all the cool new features from ES6
* and even more. Enjoy!
*/
const name = 1
const description = 'Yo ' + name + '! How are you doing? ' + 1
let tips = [
"Click on any AST node with a '+' to expand it",
"Hovering over a node highlights the \
corresponding location in the source code",
"Shift click on an AST node to expand the whole subtree"
];
function printTips() {
tips.forEach((tip, i) => console.log(`Tip ${i}:` + tip));
}
/**
* Paste or drop some JavaScript here and explore
* the syntax tree created by chosen parser.
* You can use all the cool new features from ES6
* and even more. Enjoy!
*/
const name = 1
const description = 'Yo ' + name + '! How are you doing? ' + 1
let tips = [
"Click on any AST node with a '+' to expand it",
"Hovering over a node highlights the \
corresponding location in the source code",
"Shift click on an AST node to expand the whole subtree"
];
function printTips() {
for (const i in tips) {
const tip = tips[i];
console.log(`Tip ${i}:` + tip);
};
}
// jscodeshift can take a parser, like "babel", "babylon", "flow", "ts", or "tsx"
// Read more: https://github.com/facebook/jscodeshift#parser
// Press ctrl+space for code completion
export default function transformer(file, api) {
const j = api.jscodeshift;
j;
return j(file.source)
.find(j.CallExpression, {
callee: {
type: "MemberExpression",
property: { type: "Identifier", name: "forEach" },
},
})
.replaceWith((path) => {
const funcNode = path.node.arguments[0];
const name = path.node.callee.object.name;
const [valueNode, indexNode] = funcNode.params;
const handlerNode = funcNode.body;
const variable = j.variableDeclaration("const", [
j.variableDeclarator(
j.identifier(valueNode.name),
j.memberExpression(
j.identifier(name),
j.identifier(indexNode.name),
true
)
),
]);
const body = j.blockStatement([
variable,
j.expressionStatement(handlerNode),
]);
const left = j.variableDeclaration("const", [
j.identifier(indexNode.name),
]);
const right = j.identifier("tips");
return j.forInStatement(left, right, body);
})
.toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment