expr-eval

repository·master·Indexed 23 days ago

https://github.com/silentmatt/expr-eval

A JavaScript library for parsing and evaluating mathematical expressions, providing a safer, math-oriented alternative to native eval(). It features a Parser class for converting strings into Expression objects, which can be evaluated with variables, simplified, or converted into native JavaScript functions. The library supports arithmetic, logical, and comparison operators, built-in mathematical and array functions, and allows for custom functions and constants.

Tokens
3K
Snippets
3
Records
27
Agent score
78%

What's inside expr-eval

  1. Expression Syntax: Function Definitions

    master

    You can define functions directly within an expression using the syntax name(params) = expression. These functions become available in the scope when the expression is evaluated.

    square(x) = x*x
    add(a, b) = a + b
    factorial(x) = x < 2 ? 1 : x * factorial(x - 1)
  2. Basic Usage of expr-eval

    master

    You can use expr-eval by either creating a Parser instance for more control or using the static Parser.evaluate method for quick calculations.

    Using a Parser instance allows you to parse an expression once into an Expression object and then evaluate it multiple times with different variables, or even convert it to a native JavaScript function.

    const Parser = require('expr-eval').Parser;
    
    // Method 1: Using a Parser instance
    const parser = new Parser();
    let expr = parser.parse('2 * x + 1');
    console.log(expr.evaluate({ x: 3 })); // 7
    
    // Method 2: Static evaluation
    Parser.evaluate('6 * x', { x: 7 }) // 42
  3. Define custom JavaScript functions in Parser

    master

    You can extend the expression language by adding your own JavaScript functions to a Parser instance via its functions property. This property is an object containing all functions currently in scope.

    const parser = new Parser();
    
    // Add a new function
    parser.functions.customAddFunction = function (arg1, arg2) {
      return arg1 + arg2;
    };
    
    // Remove a function
    delete parser.functions.fac;
    
    parser.evaluate('customAddFunction(2, 4) == 6'); // true
  4. Use the Expression class

    master

    An Expression object is returned by Parser.parse(). It represents a parsed mathematical formula that can be manipulated or evaluated.

    • evaluate(variables?: object): Evaluates the expression using the provided variables. Throws an exception if variables are unbound.
    • substitute(variable: string, expression: Expression | string | number): Returns a new Expression where a specific variable is replaced by another expression (function composition).
    • simplify(variables: object): Performs partial evaluation by replacing constant sub-expressions and variable references with literal values.
    • variables(options?: object): Returns an array of unbound variables. Use { withMembers: true } to get the full object path (e.g., ['x.y.z'] instead of ['x']).
    • symbols(options?: object): Returns an array of all symbols, including variables and built-in functions used. Supports { withMembers: true }.
    • toString(): Returns the string representation of the expression, including parentheses for debugging precedence.
    • toJSFunction(parameters: array | string, variables?: object): Converts the expression into a native, callable JavaScript function. If variables are provided, the expression is simplified with those values before conversion.
  5. Use the Parser class

    master

    The Parser class is the primary entry point for the library.

    • new Parser([options]): Constructs a new instance. options allows configuring enabled/disabled operators.
    • parse(expression: string): Converts a string expression into an Expression object.
    • static Parser.parse(expression: string): Static helper to parse an expression without manually instantiating a Parser.
    • static Parser.evaluate(expression: string, variables?: object): Parses and immediately evaluates an expression. Equivalent to Parser.parse(expr).evaluate(vars).
  6. Configure Parser operators

    master

    When constructing a new Parser, you can pass an options object to enable or disable specific groups of operators. By default, most operators are enabled. This is useful for restricting the expression language for security or specific use cases.

    Supported operator groups include:

    • add, subtract, multiply, divide, remainder, power, factorial, concatenate (Arithmetic)
    • logical (and, or, not)
    • comparison (<, >, ==, !=, etc.)
    • in (the in operator)
    • assignment (= operator)
    const parser = new Parser({
      operators: {
        add: true,
        concatenate: true,
        conditional: true,
        divide: true,
        factorial: true,
        multiply: true,
        power: true,
        remainder: true,
        subtract: true,
    
        // Disable and, or, not, <, ==, !=, etc.
        logical: false,
        comparison: false,
    
        // Disable 'in' and = operators
        'in': false,
        assignment: false
      }
    });
  7. Define custom constants in Parser

    master

    The parser includes pre-defined constants like E, PI, true, and false. You can customize these via the parser.consts property.

    const parser = new Parser();
    parser.consts.R = 1.234;
    
    console.log(parser.parse('A+B/R').toString());  // ((A + B) / 1.234)
    
    // To disable all pre-defined constants:
    parser.consts = {};
  8. Configure operator availability with Parser options

    master

    You can restrict which operators are available in your expressions by passing an operators object in the Parser constructor. The keys in this object correspond to the internal option names of the operators.

    To disable an operator, set its option name to false in the operators object. If an operator is not mentioned, it is enabled by default.

    Operator Option Name Mapping:

    • +: add
    • -: subtract
    • *: multiply
    • /: divide
    • %: remainder
    • ^: power
    • !: factorial
    • <, >, <=, >=, ==, !=: comparison
    • ||: concatenate
    • and, or, not: logical
    • ?, :: conditional
    • =: assignment
    • [: array
    • ()=: fndef`
  9. Expression Syntax: Operators and Precedence

    master

    The grammar is math-oriented. Note that ^ is exponentiation (not XOR).

    OperatorAssociativityDescription
    (...)NoneGrouping
    f(), x.y, a[i]LeftFunction call, property access, array indexing
    !LeftFactorial
    ^RightExponentiation
    +, -, not, sqrt, etc.RightUnary prefix operators
    *, /, %LeftMultiplication, division, remainder
    +, -, ||LeftAddition, subtraction, array/list concatenation
    ==, !=, >=, <=, >, <, inLeftComparison (including in for array membership)
    andLeftLogical AND
    orLeftLogical OR
    x ? y : zRightTernary conditional
    =RightVariable assignment
    ;LeftExpression separator
  10. Expression Syntax: Pre-defined Functions

    master

    The parser includes several built-in functions:

    FunctionDescription
    random(n)Random number in range [0, n) (defaults to [0, 1))
    min(a,b,...)Smallest number in list
    max(a,b,...)Largest number in list
    hypot(a,b)Hypotenuse $\sqrt{a^2 + b^2}$
    pow(x, y)$x^y$
    atan2(y, x)Arc tangent of $x/y$
    roundTo(x, n)Round $x$ to $n$ decimal places
    map(f, a)Array map: applies function f to each element of array a
    fold(f, y, a)Array fold/reduce: y = f(y, x, index)
    filter(f, a)Array filter: returns elements where f(x, index) is true
    indexOf(x, a)First index of x in array/string a
    join(sep, a)Concatenate elements of a with sep
    if(c, a, b)Function form of c ? a : b (Note: always evaluates both a and b)
  11. Expression Syntax: Unary Operators

    master

    Unary operators can be used without parentheses (e.g., sin x). If parentheses are used, they have the same precedence as function calls.

    Common unary operators include:

    • -x: Negation
    • +x: Unary plus (converts operand to number)
    • x!: Factorial
    • abs x: Absolute value
    • sin x, cos x, tan x, etc.: Trigonometric functions
    • sqrt x: Square root
    • log x: Natural logarithm
    • floor x, ceil x, round x: Rounding functions
    • not x: Logical NOT