Overview
@inzero/expr-eval Is a context-based expression parser and evaluator.
Installation
npm install @inzero/expr-evalSupported syntax
Literals
evalExpr(`"abc"`); // "abc"
evalExpr(`123`); // 123
evalExpr(`true`); // true
evalExpr(`undefined`); // undefined
evalExpr(`null`); // nullIdentifiers & Member Access
evalExpr(`x`, { x: 999 }); // 999
evalExpr(`user.age`, { user: { age: 18 } }); // 18Functions
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); // falseConditions
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`); // -1Concat
evalExpr(`"(" + x + ")"`, { x: "c4" }); // "(c4)"Math
evalExpr(`(1 + 2 * 3) ** 4)`); // 2401Quick 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 }); // trueNext
- 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.