JavaScript および TypeScript 向けの高速かつ軽量な式評価エンジン。
親しみやすい API、依存関係ゼロ、完全な TypeScript サポートを備えたモダンな式パーサーです。
npm install safe-expr-eval
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 })); // 21
import { evaluate } from 'safe-expr-eval';
const result = evaluate('10 + 5 * 2');
console.log(result); // 20
import { compile } from 'safe-expr-eval';
const fn = compile('price * quantity * (1 - discount)');
console.log(
fn({
price: 100,
quantity: 2,
discount: 0.1
})
); // 180
+ - * / %
== != > < >= <=
and or not
&& || !
Numbers → 42, 3.14
Strings → "hello"
Booleans → true, false
Variables → price, user.name
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
})
); // 30
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
})
); // 115
new Parser()
parser.parse(expression)
parser.evaluate(expression, variables?)
parser.functions
parser.consts
evaluate(expression, variables?)
compile(expression)
npm test
npm run test:coverage
MIT
詳細は LICENSE ファイルを参照してください。
プルリクエストやコントリビューションを歓迎します。
バグを見つけた場合や機能リクエストがある場合は、Issue を開いてください。
Alejandro Castrillon
GitHub: https://github.com/