Created
October 18, 2012 18:31
-
-
Save beatak/3913966 to your computer and use it in GitHub Desktop.
testing esprima/escodegen 2
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
#!/usr/local/bin/node | |
var parse = require('esprima').parse; | |
var generate = require('escodegen').generate; | |
var codes = [ | |
"console.log('a', 'b', 'c');", | |
"console.log('a');", | |
"console.log();" | |
]; | |
var scan = function (ast) { | |
var replacement = strip(ast, 0, ast.body[0]); | |
if (false === replacement) { | |
ast.body.splice(0, 1); | |
} | |
else { | |
console.log( 'replace: ' + JSON.stringify(replacement, null, 2) ); | |
ast.body[0].expression = replacement; | |
} | |
}; | |
var strip = function (parent, index, tree) { | |
var len = tree.expression.arguments.length; | |
var result; | |
if (0 === len) { | |
result = false; | |
} | |
else if (1 === len) { | |
result = tree.expression.arguments[0]; | |
} | |
else { | |
result = { | |
type: 'SequenceExpression', | |
expressions: tree.expression.arguments | |
}; | |
} | |
return result; | |
}; | |
codes.forEach( | |
function (code) { | |
var ast; | |
console.log('modify this: ' + code); | |
console.log( '====' ); | |
ast = parse(code); | |
scan(ast); | |
console.log( JSON.stringify( ast, null, 2) ); | |
console.log( '====' ); | |
console.log( generate(ast) ); | |
console.log( '====' ); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment