jsep
jsep copied to clipboard
Exposing the eval code in the API or the doc
Hi there, jsep looks wonderful.
One thing that might be obvious to people familiar with esprima is that it is trivial to evaluate the generated AST:
var do_eval = function(node) {
if(node.type === "BinaryExpression") {
return binops[node.operator](do_eval(node.left), do_eval(node.right));
} else if(node.type === "UnaryExpression") {
return unops[node.operator](do_eval(node.argument));
} else if(node.type === "Literal") {
return node.value;
}
};
I found it in the tests and it was not obvious to me.
I hope this helps Many thanks!
Wrote this module to help with this. It doesn't eval, but it'll generate a string: https://github.com/lapwinglabs/jsepgen
Thank you for this!
I just put together a small module for evaluation and compilation.
Evaluation:
// Evaluation
expr.eval('a + b / c', {a: 2, b: 2, c: 5}); // 0.8
Compilation:
const fn = expr.compile('foo.bar + 10');
fn({foo: {bar: 'baz'}}); // 'baz10'
There's not much to it, besides what's already shown in the tests and explained above. @soney, would you take a PR adding those functions to the core library? Or, if this doesn't exist elsewhere, would you prefer that it remain a separate repo with attribution to jsep?
I should add — even though the module above avoids use of eval() for execution, there are still security risks you should be aware of when using it.