@inzero/expr-eval

Overview

@inzero/expr-eval Is a context-based expression parser and evaluator.

Installation

npm install @inzero/expr-eval

Supported syntax

Literals

evalExpr(`"abc"`); // "abc"
evalExpr(`123`); // 123
evalExpr(`true`); // true
evalExpr(`undefined`); // undefined
evalExpr(`null`); // null

Identifiers & Member Access

evalExpr(`x`, { x: 999 }); // 999
evalExpr(`user.age`, { user: { age: 18 } }); // 18

Functions

const ctx = { user: { displayName: "VIP_inzero" } };

evalExpr(`startsWith(user.displayName, 'VIP_')`, ctx); // true

// If the function you're using has exactly 2 parameters, then you can write it like this:
evalExpr(`user.displayName @startsWith 'VIP_'`, ctx); // true

// And to do `!foo()`, you can write
evalExpr(`user.displayName !@startsWith 'VIP_'`, ctx); // false

Conditions

evalExpr(`(user.isAdmin && user.age >= 18) === true`, { user: { isAdmin: true, age: 22 } }); // true
evalExpr(`user ? user.name : 'foo'`, {}); // 'foo'

Unary

evalExpr(`!true`); // false
evalExpr(`+true`); // 1
evalExpr(`-true`); // -1

Concat

evalExpr(`"(" + x + ")"`, { x: "c4" }); // "(c4)"

Math

evalExpr(`(1 + 2 * 3) ** 4)`); // 2401

Quick Examples

import { evalExpr } from "@inzero/expr-eval";

evalExpr(`1 + 2 * 3`); // 7
evalExpr(`(x + y * z) > PI`, { x: 1, y: 2, z: 3, PI: Math.PI }); // true

Next

  • compileExpr(): Parses and compiles an expression once, returning a reusable evaluator for different context objects.
  • evalExpr(): Parses and evaluates an expression in a single call.
  • Customization: Customize the aliases and functions.

On this page