safe-expr-eval
v1.0.4
Published
Secure expression evaluator - Drop-in replacement for expr-eval without CVE-2025-12735 vulnerability
Maintainers
Readme
safe-expr-eval
Fast and lightweight expression evaluator for JavaScript and TypeScript.
A modern expression parser with a familiar API, zero dependencies, and full TypeScript support.
Features
- Fast expression parsing and evaluation
- Lightweight and dependency-free
- Full TypeScript support
- Simple and familiar API
- Custom functions and constants
- ES2020+ compatible
- Well tested
Installation
npm install safe-expr-evalQuick Start
Basic Usage
import { Parser } from 'safe-expr-eval';
const parser = new Parser();
const expr = parser.parse('2 * x + 1');
console.log(expr.evaluate({ x: 3 })); // 7
console.log(expr.evaluate({ x: 10 })); // 21Direct Evaluation
import { evaluate } from 'safe-expr-eval';
const result = evaluate('10 + 5 * 2');
console.log(result); // 20Compiled Expressions
import { compile } from 'safe-expr-eval';
const fn = compile('price * quantity * (1 - discount)');
console.log(
fn({
price: 100,
quantity: 2,
discount: 0.1
})
); // 180Supported Operations
Arithmetic
+ - * / %Comparison
== != > < >= <=Logical
and or not
&& || !Data Types
Numbers → 42, 3.14
Strings → "hello"
Booleans → true, false
Variables → price, user.nameCustom Functions
const parser = new Parser();
parser.functions.max = Math.max;
parser.functions.min = Math.min;
parser.functions.round = Math.round;
const expr = parser.parse(
'round(max(a, b) * 1.5)'
);
console.log(
expr.evaluate({
a: 10,
b: 20
})
); // 30Constants
const parser = new Parser();
parser.consts.PI = Math.PI;
parser.consts.TAX_RATE = 0.15;
const expr = parser.parse(
'price * (1 + TAX_RATE)'
);
console.log(
expr.evaluate({
price: 100
})
); // 115API
Parser
Create parser
new Parser()Parse expression
parser.parse(expression)Evaluate expression
parser.evaluate(expression, variables?)Functions registry
parser.functionsConstants registry
parser.constsStandalone Functions
evaluate
evaluate(expression, variables?)compile
compile(expression)Testing
npm testnpm run test:coverageLicense
MIT
See the LICENSE file for details.
Contributing
Pull requests and contributions are welcome.
Issues
Please open an issue if you find a bug or have a feature request.
Author
Alejandro Castrillon
GitHub: https://github.com/