Package Exports
- json-expression-eval
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 (json-expression-eval) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
json-expression-eval
A Node.js module that evaluates a json described boolean expression using dynamic functions
Installation
npm install json-expression-eval --save
yarn add json-expression-eval
Usage
Please see tests for more usages and example dir for extended and opinionated usage.
API
This module enables you to evaluate boolean expressions which are described using a JSON structure and can utilize user defined 'functions'.
There are 4 types op operators you can use (evaluated in that order of precedence):
and
- accepts a non empty list of operatorsor
- accepts a non empty list of operatorsnot
- accepts another operator<user defined funcs>
- accepts any type of argument and evaluated by the user defined functions and given context.<compare funcs>
- operates on one of the context properties and compare it to a given value.{property: {op: value}}
- available ops:
gt
- >gte
- >=lt
- <lte
- <=eq
- ===neq
- !==
- available ops:
{property: value}
- compares the property to that value (shorthand to the
eq
op)
- compares the property to that value (shorthand to the
Example expressions, assuming we have the user
and maxCount
user defined functions in place can be:
{
"or":[
{
"not":{
"user":"a@b.com"
}
},
{
"maxCount":1
},
{
"times": { "eq" : 5}
},
{
"country": "USA"
}
]
}
Javascript
const evaluator = require('json-expression-eval');
const functionsTable = {
user: (user, context) => {
return context.userId === user;
},
maxCount: (maxCount, context) => {
return context.times < maxCount;
}
};
const result = evaluator.evaluate({or:[{user: 'a@b.com'},{not: {and: [{maxCount: 1},{user: 'a2@b.com'}]}}]},{userId:'a@b.com', times: 1},functionsTable);
Output should be 'true'
TypeScript
import { evaluate } from 'json-expression-eval';
const functionsTable : FunctionsTable = {
user: (user :string , context : { userId: string }): boolean => {
return context.userId === user;
},
maxCount: (maxCount: number, context: { times: number }): boolean => {
return context.times < maxCount;
}
};
const result = evaluate({or:[{user: 'a@b.com'},{not: {and: [{maxCount: 5},{user: 'a2@b.com'}]}}]},{userId:'a2@b.com', times: 1},functionsTable);
Output should be 'false'
Test
npm run test