safe-evaluate-expression
Small library to dynamically create and evaluate expression with multiple parameters (even undefined). It also offer an ancillary function to protect lambda function to undefined params inputs.
Installation
npm install safe-evaluate-expression
Usage
evaluate(expression:[String], params:[Object])
Example
const evaluate = require("safe-evaluate-expression");
evaluate("a > 1", { a: 3 });
Advanced Example
const evaluate = require("safe-evaluate-expression");
const operators = {
isUndefined: (x) => x === undefined,
isEqual: (a, b) => a === b,
isGreater: (a, b) => a > b,
isLower: (a, b) => a < b,
};
const vars = { a: 1, b: 1, c: 2 };
const params = { ...vars, ...operators };
evaluate("isEqual(a,b)", params);
evaluate("isEqual(a,c)", params);
evaluate("isEqual(a,notDefined)", params);
evaluate("isUndefined(a)", params);
evaluate("isUndefined(notDefined)", params);
evaluate("(isUndefined(notDefined) || (isGreater(c, a) && isLower(b, c))) && isEqual(a,1)", params);
Default lambda undefined params
protectedLambda(lamdaFunc, [undefined dafalut])
Protect lambda function by assigning a default value for undefined input paramters.
const { defaultLambda } = require("safe-evaluate-expression");
const lambda = (a, b, c) => a + b + c;
const protectedLambda = defaultLambda(lambda, 0);
console.log(lambda(), protectedLambda());