Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exposing the eval code in the API or the doc #13

Open
hmalphettes opened this issue Aug 13, 2014 · 4 comments
Open

Exposing the eval code in the API or the doc #13

hmalphettes opened this issue Aug 13, 2014 · 4 comments

Comments

@hmalphettes
Copy link

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!

@matthewmueller
Copy link

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

@oliverjanik
Copy link

Thank you for this!

@donmccurdy
Copy link

donmccurdy commented Apr 12, 2017

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
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants