Skip to content

Instantly share code, notes, and snippets.

@rcanepa
Last active May 21, 2017 02:09
Show Gist options
  • Save rcanepa/ae230f2906397452bc51c01e6ca1fedd to your computer and use it in GitHub Desktop.
Save rcanepa/ae230f2906397452bc51c01e6ca1fedd to your computer and use it in GitHub Desktop.
Playing with ASTs (Babelv6)

Add the line and column as the first argument on every console.log call.

export default function(babel) {
const { types: t } = babel;
return {
name: "consoleImproved",
visitor: {
CallExpression(path) {
if (path.node.callee.object && path.node.callee.object.name === "console") {
const parentFunction = path.findParent(t.isFunctionDeclaration);
const parentFunctionExpression = path.findParent(t.isFunctionExpression);
const parentArrowFunction = path.findParent(t.isArrowFunctionExpression);
const startConsole = path.node.loc.start;
let helperMessage = `${startConsole.line}:${startConsole.column}`;
if (parentFunction) {
helperMessage = `${parentFunction.node.id.name} ${helperMessage}`;
} else if (parentArrowFunction) {
helperMessage = `${parentArrowFunction.parent.id.name} ${helperMessage}`;
} else if (parentFunctionExpression) {
helperMessage = `${parentFunctionExpression.parent.id.name} ${helperMessage}`;
}
path.node.arguments.unshift(t.stringLiteral(helperMessage));
}
}
}
};
}
function add(a, b) {
console.log("add 2:2", a, b)
return a + b
}
function subtract(a, b) {
console.log("subtract 7:2", a, b)
return a - b
}
const multiply = (a, b) => {
console.log("multiply 12:2", a, b)
return a * b
}
const divide = function(a, b) {
console.log("divide 17:2", a, b)
return a / b
}
add(1, 2)
subtract(2, 1)
multiply(3, 4)
divide(25, 5)
console.log("25:0", 'sup dawg')
function add(a, b) {
console.log(a, b)
return a + b
}
function subtract(a, b) {
console.log(a, b)
return a - b
}
const multiply = (a, b) => {
console.log(a, b)
return a * b
}
const divide = function(a, b) {
console.log(a, b)
return a / b
}
add(1, 2)
subtract(2, 1)
multiply(3, 4)
divide(25, 5)
console.log('sup dawg')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment