Get started with acorn-walk CDN
MIT licensed
Acorn-Walk: JS parser with iterative interface for AST traversal and transformation by Acorn.
Tags:- javascript
- ast
- walker
- parser
Stable version
Copied!
How to start using acorn-walk CDN
<!DOCTYPE html>
<html>
<head>
<title>Get started with acorn-walk CDN - cdnhub.io</title>
<script src="https://cdn.cdnhub.io/acorn-walk/8.3.2/walk.js"></script>
</head>
<body>
<script>
const code = `
function add(a, b) {
return a + b;
}
const numbers = [1, 2, 3];
const sum = numbers.reduce(add);
console.log(sum);
`;
const ast = require('acorn').parse(code, { ecmaVersion: 6 });
const visitor = {
Identifier(path) {
if (path.node.name === 'sum') {
path.value = sum;
}
},
ExpressionStatement(path) {
if (path.node.expression.type === 'CallExpression' && path.node.expression.callee.type === 'Identifier' && path.node.expression.callee.name === 'console' && path.node.expression.arguments[0].type === 'Identifier' && path.node.expression.arguments[0].name === 'log') {
const expression = path.get('expression.arguments[0]');
const value = expression.value;
if (value.type === 'Identifier' && value.name === 'sum') {
path.replaceWith(new acorn.ExpressionStatement(new acorn.ExpressionStatement(new acorn.AssignmentExpression('=', new acorn.Identifier('result'), new acorn.NumericLiteral(value.value)))));
path.node.expression.arguments[0] = new acorn.Identifier('result');
}
}
}
};
const traverse = require('acorn-walk').default;
traverse(ast, visitor);
const compiled = require('babel-core').compile(ast.body[0], { presets: ['es2015'] }).code;
new Function('sum', 'result', compiled)[sum](1, 2, 3);
console.log('Result:', result); // Output: Result: 6
</script>
</body>
</html>
Copied!
Copied!