simple-eval
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

simple-eval

Simple JavaScript expression evaluator.

Install

yarn add simple-eval

or if npm is package manager of your choice

npm install simple-eval --save

Usage

import simpleEval from 'simple-eval';

simpleEval('2 + 4 * 10 + -4'); //  38
simpleEval('Math.floor(Math.PI * 10)'); // exception 
simpleEval('Math.floor(Math.PI * 10)', { Math }); // 31, works because we provided Math
simpleEval('foo.bar.baz ? 10 : Math.random()', {
  Math,
  foo: {
    bar: {
      baz: false,
    }
  }
}); // some random number, as returned by Math.random()

By default, simple-eval uses jsep, but you're free to use any ESTree compliant parser such as acorn, @babel/parser, or esprima.

Caveats

Although a number of use cases is supported, do note that this library does not aim to be a drop-in replacement for eval. By supporting a limited set of instructions, it's arguably safer than eval, albeit it's still not supposed to be used instead of proper sandbox. In particular, all kind of declarations and assignments are prohibited.

LICENSE

MIT

Package Sidebar

Install

npm i simple-eval

Weekly Downloads

411,821

Version

1.0.1

License

MIT

Unpacked Size

11.3 kB

Total Files

9

Last publish

Collaborators

  • p0lip