morph-expressions

An extremely efficient and flexible parser for Math or Logical expression using Javascript. It has all the basic functions supported with extensive support for new functions, variable etc.

Usage no npm install needed!

<script type="module">
  import morphExpressions from 'https://cdn.skypack.dev/morph-expressions';
</script>

README

morph-expressions

An extremely efficient and flexible parser for Math or Logical expression using Javascript. It has all the basic functions supported with extensive support for new functions, variable etc.

Build Status Coverage Status David npm MIT NPM Version

Install

$ npm install morph-expressions

Usage

import Parser from 'morph-expressions';
const parser = new Parser();

const compiled = parser.parse('1 + 1');
compiled.eval(); // returns 2

You can also specify scope:

const compiled = parser.parse('x + 1 - y == 0');
compiled.identifiers; // ['x', 'y'] - returns list of identifiers, which used in expression
compiled.eval({ x: 2, y: 3 }); // returns true

//Or

parser.parseAndEval('x + 1 - y == 0', { x: 2, y: 3 });  // returns true
parser.parseAndEval('foo.bar[1] == 5', { foo: { bar: [4, 5, 6] } });  // returns true

For register the custom function or computed properties

parser.registerFunction('sqr', value => value * value);
parser.registerProperty('foo', scope => 'bar');

parser.parseAndEval('sqr(sqr(x))', { x: 2 });  // returns 16
parser.parseAndEval('foo', { x: 2 });  // returns 'bar'

Test

To execute tests for the library, install the project dependencies once:

npm install

Then, the tests can be executed:

npm test