🚀 Big News:Socket Has Acquired Secure Annex.Learn More →
Socket
Book a DemoSign in
Socket

expressionparser

Package Overview
Dependencies
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

expressionparser

Parse simple expressions, in a language of your own description

Source
npmnpm
Version
1.1.7
Version published
Weekly downloads
5.5K
-5.76%
Maintainers
1
Weekly downloads
 
Created
Source

Expression Parser

A no-dependency, easy-to-extend interpreter for parsing and evaluating expressions.

This project is just a single file, aiming to be easy to understand, extend, and build upon.

Install

npm install expressionparser

Built-in Languages

A built-in language called "formula" is provided as the default.

Evaluating an expression:

import { init, formula } from 'expressionparser'

const parser = init(formula, (term: string) => {
  if (term === "MY_VARIABLE") {
    return 42;
  } else {
    throw new Error(`Invalid term: ${term}`);
  }
});

parser.expressionToValue("(1 + 1) + 40 = MY_VARIABLE"); // true

Custom Language

Parse simple expressions, in a language of your own description, such as:

(A AND B) OR NOT (C OR D)

or

1 + 1 * 2 - (10 / 2) + SQRT 16

The latter language can be configured as follows:

const arithmeticLanguage = {
  INFIX_OPS: {
    '+': function(a, b) {
      return a + b;
    },
    '-': function(a, b) {
      return a - b;
    },
    '*': function(a, b) {
      return a * b;
    },
    '/': function(a, b) {
      return a / b;
    },
    ',': function(a, b) {
      return [a] + b;
    }
  },
  PREFIX_OPS: {
    'SQRT': function(expr) {
      return Math.sqrt(expr);
    },
    'POW': function(expr) {
      return Math.pow(expr[0], expr[1]);
    }
  },
  PRECEDENCE: [['SQRT', 'POW'], ['*', '/'], ['+', '-'], [',']],
  GROUP_OPEN: '(',
  GROUP_CLOSE: ')',
  SEPARATORS: [','],
  WHITESPACE_CHARS: [" "],
  SYMBOLS: ['(', ')', '+', '-', '*', '/', ','],

  termDelegate: function(term) {
    return parseInt(term);
  }
};

and evaluated as: const expr = 'pow(1 + 1 * 2 - (10 / 2) + sqrt(16), 2)'.toUpperCase(); const result = new ExpressionParser(arithmeticLanguage).expressionToValue(expr);

(which will result in 4)

Tokeniser

This uses the built-in tokeniser (which is very simple), but you can write your own tokeniser (e.g. for differentiating between prefix minus and infix minus) and pass the tokens into:

const result = new ExpressionParser(arithmeticLanguage).evaluateTokens(['1', '+', '1']);

(which will also result in 2)

RPN

This parser will also convert between an expression and a Reverse Polish Notation (RPN) list:

const parser = new ExpressionParser();

parser.expressionToRpn(expr); // returns RPN list
parser.tokensToRpn(exprTokenList); // returns RPN list
parser.rpnToExpression(rpnList); // returns expression string
parser.rpnToTokens(rpnList); // returns expression token list

Further configuration

The SEPARATORS, WHITESPACE_CHARS, and SYMBOLS options are to assist the built-in tokeniser and expression string builder. By default terms used to define operators or terms are strings of characters separated by any member of WHITESPACE_CHARS. Characters in SYMBOLS will be collected as a separate category to any other characters.

e.g. If '!' is in SYMBOLS, with ' ' in WHITESPACE_CHARS, we can use "!!A" instead of "!! A" to provide the tokenization of ["!!", "A"]

SEPARATORS are single-character symbols which are self-terminating (they stand on their own).

e.g. If '!' is instead in SEPARATORS, "!!A" will be tokenized to: ["!", "!", "A"]

The termDelegate option is used to evaluate the terminal symbols in the parse tree (i.e. the values).

Keywords

parser

FAQs

Package last updated on 20 Mar 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts