Skip to content

Evaluates javascript expressions using jsep. Valid expression types and binary/unary operators is configurable.

License

Notifications You must be signed in to change notification settings

betastreet/jsep-eval

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jsep-eval: evaluate javascript expressions

jsep-eval evaluates javascript expressions, and uses jsep to parse the expressions. A context can/should be supplied against which identifers are matched.

Usage

Node.JS

First, run npm install jsep-eval. Then, in your source file:

const JsepEval = require("jsep-eval");
const evaluate = new jsepEval().evaluate;
const two = evaluate('1 + 1');
const three = evaluate('two + 1', {two: 2});

Configure evaluation restrictively

jsep-eval exposes the objects the allowed expression types

const types = jsepEval.types;

So it is possible to dis-allow a given expression type by removing it from this array:

const types = jsepEval.types;
evaluate('2 + 2'); // returns 4
delete types.BINARY;
evaluate('2 + 2'); // throws error

It is also possible to restrict evaluation by operator (both binary and unary):

const binaryOps = jsepEval.operators.binary;
const unaryOps = jsepEval.operators.unary;

evaluate('2 === 2'); // returns true
delete binaryOps['==='];
evaluate('2 === 2'); // throws error

evaluate('!false'); // returns true
unaryOps['!'] = () => 'bob';
evaluate('!false'); // returns 'bob'

It is also possible to override or add operators:

const stringEqual = (a, b) => _.isString(a) && _.isString(b) && a.localeCompare(b, undefined, { sensitivity: 'accent'}) === 0;
jsepEval.addBinaryOp('==', (a, b) => (a == b || stringEqual(a, b)));
expect(jsepEval.evaluate('"a" == "A"')).toBe(true);

For more examples, see the unit tests

License

jsep-eval is under the MIT license. See LICENSE file.

About

Evaluates javascript expressions using jsep. Valid expression types and binary/unary operators is configurable.

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%