Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

safe-evaluate-expression

Package Overview
Dependencies
Maintainers
1
Versions
28
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

safe-evaluate-expression - npm Package Compare versions

Comparing version 1.0.7 to 1.0.8

examples/evaluate.js

83

index.js

@@ -1,78 +0,5 @@

//**************************************************************
// RegEx to find parameters, comments and arguments
//**************************************************************
const FUNC_PARAMS_SIMPLE = /\b\w+(\b(?!\())/g;
const FUNC_PARAMS = /[\"|\']?\w+(\b(?!\())\b[\"|\']?/g;
const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;
const ARGUMENT_NAMES = /([^\s,]+)/g;
//**************************************************************
// Returns regular function parameters names
//**************************************************************
function getParamNames(func) {
const fnStr = func.toString().replace(STRIP_COMMENTS, "");
const result = fnStr.slice(fnStr.indexOf("(") + 1, fnStr.indexOf(")")).match(ARGUMENT_NAMES);
return result || [];
}
//**************************************************************
// Returns lambda function body
//**************************************************************
function getLambdaBody(func) {
const fnStr = func.toString().replace(STRIP_COMMENTS, "");
return fnStr.substring(fnStr.indexOf("=>") + 3);
}
//**************************************************************
// Wrap a param in a try-catch to handle undefined params
//**************************************************************
const makeSafeParam = (param, undef) => {
const wrap = `(() => {
try {
return ${param} !== undefined ? ${param} : ${undef};
} catch (e) {
return ${undef};
}
})()`;
return wrap;
};
//**************************************************************
// Wrap every function and sub-function param in a safe
// try-catch to handle undefined
//**************************************************************
const makeSafe = (str, undef) => str.replace(FUNC_PARAMS, (p) => makeSafeParam(p, undef));
//**************************************************************
// Stringify params object and dynamically build
// function that evaluate the expression body
//**************************************************************
const evaluate = (body, params, undef) => {
const input = `{${Object.keys(params)
.map((k) => k)
.join(",")}}`;
const func = new Function(input, `return ${makeSafe(body, undef)}`);
return func(params);
};
//**************************************************************
// Get a lambda function as input and optiona parameters
// to default undefined params in returnd function
//**************************************************************
function defaultLambda(func, undef) {
const expression = getLambdaBody(func).trim();
const names = getParamNames(func);
return function (...vars) {
const params = {};
names.forEach((name, index) => (params[name] = vars[index]));
return evaluate(expression, params, undef);
};
}
module.exports = evaluate;
module.exports.defaultLambda = defaultLambda;
module.exports = require("./src/evaluate");
module.exports.factory = require("./src/factory");
module.exports.safeLambda = require("./src/safeLambda");
module.exports.putInScope = require("./src/putInScope");
module.exports.operators = require("./src/operators");
{
"name": "safe-evaluate-expression",
"version": "1.0.7",
"version": "1.0.8",
"description": "Small library to dynamically create and evaluate expression with multiple parameters (even undefined)",

@@ -5,0 +5,0 @@ "main": "index.js",

# 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._
Small library to dynamically create and evaluate expression with multiple parameters (even undefined). **To handle more sofisticate use cases is provided a [Factory](#factory) functionality to build evaluate functions with some spice 🔥**.
_It also offer an ancillary function to protect lambda function to undefined params inputs._
## Installation

@@ -11,5 +13,5 @@

## Usage
# Evaluate
### _evaluate(expression:[String], params:[Object])_
### _evaluate(expression:[String], params:[Object]) -> [expression evaluated]_

@@ -23,2 +25,4 @@ ## Example

_NB. As constant params in expression you can use only string and integers (eg. 1, "a") no floating numbers!_
## Advanced Example

@@ -49,13 +53,88 @@

## Default lambda undefined params
# Factory
### _protectedLambda(lamdaFunc, [undefined dafalut])_
### _factory(options:[Object]) -> [evaluate function]_
## Factory Params
<table>
<tr>
<th>Param</th><th>Description</th><th>Default</th>
</tr>
<tr>
<td style="vertical-align:top"><b>multipleParams</b></td>
<td>
Define if evaluate function will take a single object as params (default - eg. eval("espression",{})) or if it takes multiple params (eg. eval("espression", param1, param2, ...))
</td>
<td style="vertical-align:top">false</td>
</tr>
<tr>
<td style="vertical-align:top"><b>operatorsInScope</b></td>
<td>
Define if operators object is converted inline to have all the operators directly in the scope of the evaluation expression. If true the operators are putted in the expression context as: <b>const</b> [operatorName] = [operator]. Otherwise operators are passed thru as a single object while all operators logic inside expression are automatically prefixed. In general: use operatorsInScope = true if you use operators without external dependencies. If you use third party libraries to handle operators logic you must pass operators as an object.
</td>
<td style="vertical-align:top">false</td>
</tr>
<tr>
<td style="vertical-align:top"><b>translateLogical</b></td>
<td>
Determine if translate "AND", "OR" and "NOT" words inside expression. If true all the logical operators are converted accordingly (eg. "AND" -> &&)
</td>
<td style="vertical-align:top">false</td>
</tr>
<tr>
<td style="vertical-align:top"><b>operators</b></td>
<td>
Object containing all the operators function you want to use to evaluate expression (eg. { isEqual: (a,b) => a === b }). <i>For convenience the library export a small set of default operators.</i>
</td>
<td></td>
</tr>
<tr>
<td style="vertical-align:top"><b>undef</b>
</td>
<td>
An optional parameter to specify the value to be returned when expression occurs in undefined params.
</td>
<td style="vertical-align:top">undefined</td>
</tr>
</table>
## Factory Example
```javascript
const { factory, operators } = require("safe-evaluate-expression");
const evaluate = factory({ operators, multipleParams: true, translateLogical: true });
const metadata = { x: 1.1, y: 2 };
const list = { k: 3, z: 4 };
const map = new Map([["pi", 3.14]]);
const expression1 = "isLower(x,z)";
const expression2 = "isLower(k,y)";
evaluate(expression1, metadata, list); // -> true
evaluate(expression2, metadata, list); // -> false
evaluate(`${expression1} AND ${expression2}`, metadata, list); // -> false
evaluate(`${expression1} OR ${expression2}`, metadata, list); // -> true
const expression3 = "isLower(notDefined,z)"; // put a not defined value
evaluate(expression3, metadata, list);
evaluate(`${expression3} AND ${expression2}`, metadata, list); // -> false
evaluate(`(isLower(x,z) AND isLower(k,y) OR (isLower(z,P) AND NOT isLower(P,k)))`, metadata, list);
evaluate(`isLower(z,pi)`, metadata, list, map); // -> false
```
# Safe Lambda
### _safeLambda(lamdaFunc, [undefined defalut])_
Protect lambda function by assigning a default value for undefined input paramters.
```javascript
const { defaultLambda } = require("safe-evaluate-expression");
const { safeLambda } = require("safe-evaluate-expression");
const lambda = (a, b, c) => a + b + c;
const protectedLambda = defaultLambda(lambda, 0);
const protectedLambda = safeLambda(lambda, 0);

@@ -62,0 +141,0 @@ // The unprotected lambda returns NaN because all values are undefined

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc