jsep icon indicating copy to clipboard operation
jsep copied to clipboard

Exposing the eval code in the API or the doc

Open hmalphettes opened this issue 11 years ago • 4 comments

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!

hmalphettes avatar Aug 13 '14 01:08 hmalphettes

Wrote this module to help with this. It doesn't eval, but it'll generate a string: https://github.com/lapwinglabs/jsepgen

matthewmueller avatar Jun 18 '15 02:06 matthewmueller

Thank you for this!

oliverjanik avatar Feb 02 '16 00:02 oliverjanik

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?

donmccurdy avatar Apr 12 '17 06:04 donmccurdy

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.

donmccurdy avatar Aug 03 '18 04:08 donmccurdy