jsep vs mathjs vs math-expression-evaluator vs expr-eval
Mathematical Expression Parsing Libraries Comparison
1 Year
jsepmathjsmath-expression-evaluatorexpr-evalSimilar Packages:
What's Mathematical Expression Parsing Libraries?

Mathematical expression parsing libraries are designed to evaluate and manipulate mathematical expressions represented as strings. These libraries can parse expressions, evaluate them, and often provide additional functionalities such as simplification, variable handling, and support for complex mathematical operations. They are essential in applications that require dynamic mathematical calculations, such as calculators, data analysis tools, and educational software.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
jsep2,775,092884392 kB374 months agoMIT
mathjs1,643,37714,6399.49 MB1383 days agoApache-2.0
math-expression-evaluator1,198,90520468 kB213 months agoMIT
expr-eval541,1191,227-585 years agoMIT
Feature Comparison: jsep vs mathjs vs math-expression-evaluator vs expr-eval

Expression Parsing

  • jsep:

    jsep specializes in parsing mathematical expressions into an abstract syntax tree (AST). This allows developers to analyze and manipulate the structure of expressions, making it a great choice for building custom evaluators or interpreters.

  • mathjs:

    mathjs features a powerful parser that can handle complex expressions, including support for variables, functions, and even units. It generates an AST, allowing for advanced manipulation and evaluation of mathematical expressions.

  • math-expression-evaluator:

    math-expression-evaluator offers basic parsing capabilities to convert string expressions into evaluable formats. It is straightforward and easy to use, making it suitable for simple applications without complex parsing requirements.

  • expr-eval:

    expr-eval provides a simple parser that can handle basic arithmetic expressions and functions. It converts string expressions into a format that can be evaluated, but it does not generate an AST, making it less suitable for complex parsing needs.

Evaluation Capabilities

  • jsep:

    jsep does not evaluate expressions; it only parses them into an AST. This makes it ideal for scenarios where evaluation is handled separately or where custom evaluation logic is needed.

  • mathjs:

    mathjs offers extensive evaluation capabilities, supporting a wide range of mathematical functions, units, and complex numbers. It can evaluate expressions with high precision and is suitable for applications requiring advanced mathematical computations.

  • math-expression-evaluator:

    math-expression-evaluator provides straightforward evaluation of mathematical expressions, including support for variables and basic functions. It is user-friendly and designed for quick evaluations without complex setups.

  • expr-eval:

    expr-eval excels in evaluating expressions quickly and efficiently. It supports basic arithmetic operations, functions, and variable substitution, making it suitable for dynamic calculations in applications.

Complexity and Learning Curve

  • jsep:

    jsep has a moderate learning curve as it requires understanding of ASTs and how to manipulate them. It is best suited for developers who are comfortable with building custom evaluation logic and need detailed control over expression parsing.

  • mathjs:

    mathjs has a steeper learning curve due to its extensive features and capabilities. However, it provides comprehensive documentation and examples, making it accessible for developers willing to invest time in learning its functionalities.

  • math-expression-evaluator:

    math-expression-evaluator is straightforward and easy to learn, making it ideal for beginners or those who need a simple solution for evaluating expressions without extensive features.

  • expr-eval:

    expr-eval is easy to integrate and has a low learning curve, making it suitable for developers who need quick evaluations without delving into complex setups. Its simplicity is its main advantage.

Advanced Features

  • jsep:

    jsep is primarily a parsing library and does not include evaluation or advanced mathematical functions. It is designed for developers who need to build their own evaluation logic on top of the parsed expressions.

  • mathjs:

    mathjs stands out with a wide array of advanced features, including support for complex numbers, matrices, units, and statistical functions. It is a robust choice for applications needing extensive mathematical capabilities.

  • math-expression-evaluator:

    math-expression-evaluator offers basic support for variables and functions but lacks advanced features like unit handling or complex number support, making it suitable for simple applications.

  • expr-eval:

    expr-eval focuses on core evaluation features without additional functionalities like unit support or advanced mathematical operations, making it lightweight but limited in scope.

Community and Support

  • jsep:

    jsep has a niche community focused on expression parsing, and while it may not have extensive resources, its simplicity allows for quick understanding and implementation.

  • mathjs:

    mathjs has a large and active community, with extensive documentation, tutorials, and examples available. This makes it easier for developers to find support and resources for complex implementations.

  • math-expression-evaluator:

    math-expression-evaluator has a moderate user base with sufficient documentation, making it easy to find help for common issues and questions.

  • expr-eval:

    expr-eval has a smaller community and limited support compared to larger libraries, but it is straightforward enough that many users can self-support through documentation.

How to Choose: jsep vs mathjs vs math-expression-evaluator vs expr-eval
  • jsep:

    Select jsep if you need a library primarily for parsing mathematical expressions into an abstract syntax tree (AST) without evaluation. It is useful for building custom expression evaluators or for applications that require a deeper understanding of the expression structure.

  • mathjs:

    Choose mathjs if you require a comprehensive mathematical library that supports not only expression evaluation but also advanced mathematical functions, units, and complex number support. It is ideal for applications that need extensive mathematical capabilities and flexibility.

  • math-expression-evaluator:

    Opt for math-expression-evaluator if you need a straightforward library that can evaluate mathematical expressions with support for variables and basic functions. It is suitable for simple applications where ease of use and quick setup are priorities.

  • expr-eval:

    Choose expr-eval if you need a lightweight library focused on evaluating mathematical expressions with support for basic arithmetic operations, functions, and variables. It is ideal for applications that require quick evaluations without the need for extensive features.

README for jsep

jsep: A Tiny JavaScript Expression Parser

jsep is a simple expression parser written in JavaScript. It can parse JavaScript expressions but not operations. The difference between expressions and operations is akin to the difference between a cell in an Excel spreadsheet vs. a proper JavaScript program.

Why jsep?

I wanted a lightweight, tiny parser to be included in one of my other libraries. esprima and other parsers are great, but had more power than I need and were way too large to be included in a library that I wanted to keep relatively small.

jsep's output is almost identical to esprima's, which is in turn based on SpiderMonkey's.

Custom Build

While in the jsep project directory, run:

npm install
npm run default

The jsep built files will be in the build/ directory.

Usage

Client-side

<script type="module">
  import jsep from '/PATH/TO/jsep.min.js';
  const parsed = jsep('1 + 1');
</script>

<script src="/PATH/TO/jsep.iife.min.js"></script>
  ...
let parse_tree = jsep("1 + 1");

Node.JS

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

// ESM:
import jsep from 'jsep';
const parse_tree = jsep('1 + 1');

// or:
import { Jsep } from 'jsep';
const parse_tree = Jsep.parse('1 + 1');


// CJS:
const jsep = require('jsep').default;
const parsed = jsep('1 + 1');

// or:
const { Jsep } = require('jsep');
const parse_tree = Jsep.parse('1 + 1');

Custom Operators

// Add a custom ^ binary operator with precedence 10
// (Note that higher number = higher precedence)
jsep.addBinaryOp("^", 10);

// Add exponentiation operator (right-to-left)
jsep.addBinaryOp('**', 11, true); // now included by default

// Add a custom @ unary operator
jsep.addUnaryOp('@');

// Remove a binary operator
jsep.removeBinaryOp(">>>");

// Remove a unary operator
jsep.removeUnaryOp("~");

Custom Identifiers

You can add or remove additional valid identifier chars. ('_' and '$' are already treated like this.)

// Add a custom @ identifier
jsep.addIdentifierChar("@");

// Removes a custom @ identifier
jsep.removeIdentifierChar('@');

Custom Literals

You can add or remove additional valid literals. By default, only true, false, and null are defined

// Add standard JS literals:
jsep.addLiteral('undefined', undefined);
jsep.addLiteral('Infinity', Infinity);
jsep.addLiteral('NaN', NaN);

// Remove "null" literal from default definition
jsep.removeLiteral('null');

Plugins

JSEP supports defining custom hooks for extending or modifying the expression parsing. Plugins are registered by calling jsep.plugins.register() with the plugin(s) as the argument(s).

JSEP-provided plugins:

| | | |-----------------------------------|-------------------------------------------------------------------------------------------| | ternary | Built-in by default, adds support for ternary a ? b : c expressions | | arrow | Adds arrow-function support: v => !!v | | assignment | Adds assignment and update expression support: a = 2, a++ | | comment | Adds support for ignoring comments: a /* ignore this */ > 1 // ignore this too | | new | Adds 'new' keyword support: new Date() | | numbers | Adds hex, octal, and binary number support, ignore _ char | | object | Adds object expression support: { a: 1, b: { c }} | | regex | Adds support for regular expression literals: /[a-z]{2}/ig | | spread | Adds support for the spread operator, fn(...[1, ...a]). Works with object plugin, too | | template | Adds template literal support: `hi ${name}` | | | |

How to add plugins:

Plugins have a name property so that they can only be registered once. Any subsequent registrations will have no effect. Add a plugin by registering it with JSEP:

import jsep from 'jsep';
import ternary from '@jsep-plugin/ternary';
import object from '@jsep-plugin/object';
jsep.plugins.register(object);
jsep.plugins.register(ternary, object);

List plugins:

Plugins are stored in an object, keyed by their name. They can be retrieved through jsep.plugins.registered.

Writing Your Own Plugin:

Plugins are objects with two properties: name and init. Here's a simple plugin example:

const plugin = {
  name: 'the plugin',
  init(jsep) {
    jsep.addIdentifierChar('@');
    jsep.hooks.add('gobble-expression', function myPlugin(env) {
      if (this.char === '@') {
        this.index += 1;
        env.node = {
          type: 'MyCustom@Detector',
        };
      }
    });
  },
};

This example would treat the @ character as a custom expression, returning a node of type MyCustom@Detector.

Hooks

Most plugins will make use of hooks to modify the parsing behavior of jsep. All hooks are bound to the jsep instance, are called with a single argument, and return void. The this context provides access to the internal parsing methods of jsep to allow reuse as needed. Some hook types will pass an object that allows reading/writing the node property as needed.

Hook Types
  • before-all: called just before starting all expression parsing.
  • after-all: called after parsing all. Read/Write arg.node as required.
  • gobble-expression: called just before attempting to parse an expression. Set arg.node as required.
  • after-expression: called just after parsing an expression. Read/Write arg.node as required.
  • gobble-token: called just before attempting to parse a token. Set arg.node as required.
  • after-token: called just after parsing a token. Read/Write arg.node as required.
  • gobble-spaces: called when gobbling whitespace.
The this context of Hooks
export interface HookScope {
    index: number;
    readonly expr: string;
    readonly char: string; // current character of the expression
    readonly code: number; // current character code of the expression
    gobbleSpaces: () => void;
    gobbleExpressions: (untilICode?: number) => Expression[];
    gobbleExpression: () => Expression;
    gobbleBinaryOp: () => PossibleExpression;
    gobbleBinaryExpression: () => PossibleExpression;
    gobbleToken: () => PossibleExpression;
    gobbleTokenProperty: (node: Expression) => Expression;
    gobbleNumericLiteral: () => PossibleExpression;
    gobbleStringLiteral: () => PossibleExpression;
    gobbleIdentifier: () => PossibleExpression;
    gobbleArguments: (untilICode: number) => PossibleExpression;
    gobbleGroup: () => Expression;
    gobbleArray: () => PossibleExpression;
    throwError: (msg: string) => never;
}

License

jsep is under the MIT license. See LICENSE file.

Thanks

Some parts of the latest version of jsep were adapted from the esprima parser.