Skip to content

Instantly share code, notes, and snippets.

@Tsugami
Last active December 24, 2021 23:48
Show Gist options
  • Save Tsugami/2e893829f9fe78d23637b8081cb66a51 to your computer and use it in GitHub Desktop.
Save Tsugami/2e893829f9fe78d23637b8081cb66a51 to your computer and use it in GitHub Desktop.
My first codemod!
/**
* 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?'
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?`
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}`));
}
// jscodeshift can take a parser, like "babel", "babylon", "flow", "ts", or "tsx"
// Read more: https://github.com/facebook/jscodeshift#parser
export const parser = "tsx";
function flatten(node) {
var isBE = node.type === "BinaryExpression";
var isPLUS = node.operator === "+";
return isBE && isPLUS
? [...flatten(node.left), ...flatten(node.right)]
: [node];
}
// Press ctrl+space for code completion
export default function transformer(file, api) {
const j = api.jscodeshift;
return j(file.source)
.find(j.BinaryExpression, { operator: "+" })
.replaceWith((path) => {
const nodes = flatten(path.node);
const exps = [];
const quasis = [];
let lastStr = "";
for (const i in nodes) {
const node = nodes[i];
switch (node.type) {
case "TemplateLiteral": {
quasis.push(...node.quasis);
exps.push(...node.expressions);
break;
}
case "StringLiteral": {
lastStr += node.value;
break;
}
case "Identifier": {
const value = { cooked: lastStr, raw: lastStr };
quasis.push(j.templateElement(value, false));
exps.push(node);
lastStr = "";
}
}
}
const value = { cooked: lastStr, raw: lastStr };
quasis.push(j.templateElement(value, true));
return j.templateLiteral(quasis, exps);
})
.toSource();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment