JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 92
  • Score
    100M100P100Q85827F
  • License ISC

Small library to dynamically create and evaluate expression with multiple parameters (even undefined)

Package Exports

  • safe-evaluate-expression

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (safe-evaluate-expression) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

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 }); // -> true

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); // -> true
evaluate("isEqual(a,c)", params); // -> false
evaluate("isEqual(a,notDefined)", params); // -> false
evaluate("isUndefined(a)", params); // -> false
evaluate("isUndefined(notDefined)", params); // -> true

// It works also with infinite nested conditions
evaluate("(isUndefined(notDefined) || (isGreater(c, a) && isLower(b, c))) && isEqual(a,1)", params); // -> true

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);

// The unprotected lambda returns NaN because all values are undefined
// The protected one return zero (default): 0 + 0 + 0
console.log(lambda(), protectedLambda()); // -> NaN 0