expjson
Super lightweight, fast, and optimized evaluate-able and compilable expressions in JSON written in TypeScript
Get Started
npm install -D expjson
or
yarn add -D expjson
How to Use
compileExpression
and running it later is much faster if compiled expression is evaluated multiple times on many execution contexts.
evaluateExpression
is faster if the expression is evaluated only once.
functionalities are exactly same for both.
import {
compileExpression,
evaluateExpression,
Add,
And,
Divide,
Equal,
GreaterThan,
GreaterThanOrEqual,
IfThenElse,
In,
LessThan,
LessThanOrEqual,
Modulo,
Multiply,
Not,
NotEqual,
NotIn,
Or,
Subtract,
Var,
} from 'expjson';
expect(
evaluateExpression(
[
IfThenElse,
[In, 'admin', [Var, 'roles']],
[Not, [Var, 'postDeleted']],
[Var, 'unauthorized'],
],
{
postDeleted: false,
roles: ['user', 'admin'],
unauthorized: 'Unauthorized Error',
}
)
).toBe(true);
expect(
evaluateExpression(
[
'?:',
['In', 'admin', [Var, 'roles']],
['!', [Var, 'postDeleted']],
[Var, 'unauthorized'],
],
{
postDeleted: true,
roles: ['user', 'admin'],
unauthorized: 'Unauthorized Error',
}
)
).toBe(false);
expect(
evaluateExpression(
[
IfThenElse,
[In, 'admin', [Var, 'roles']],
[Not, [Var, 'postDeleted']],
[Var, 'unauthorized'],
],
{
postDeleted: false,
roles: ['user', 'guest'],
unauthorized: 'Unauthorized Error',
}
)
).toBe('Unauthorized Error');
const compiled1 = compileExpression([
IfThenElse,
[In, 'admin', [Var, 'roles']],
[Not, [Var, 'postDeleted']],
[Var, 'unauthorized'],
]);
expect(
compiled1({
postDeleted: false,
roles: ['user', 'admin'],
unauthorized: 'Unauthorized Error',
})
).toBe(true);
const compiled2 = compileExpression([
'?:',
['In', 'admin', [Var, 'roles']],
['!', [Var, 'postDeleted']],
[Var, 'unauthorized'],
]);
expect(
compiled2({
postDeleted: true,
roles: ['user', 'admin'],
unauthorized: 'Unauthorized Error',
})
).toBe(false);
const compiled3 = compileExpression([
IfThenElse,
[In, 'admin', [Var, 'roles']],
[Not, [Var, 'postDeleted']],
[Var, 'unauthorized'],
]);
expect(
compiled3({
postDeleted: false,
roles: ['user', 'guest'],
unauthorized: 'Unauthorized Error',
})
).toBe('Unauthorized Error');
License
MIT License