Regent: A JavaScript Rule Engine
Regent provides a lightweight framework aimed at helping you organize your application’s business logic by separating the “how” from the “why”. At the lowest level, Regent logic is written in tiny, single responsibility rules that are both self-documenting and human readable.
Installation
npm install --save regent
Implementation
For our first example, we’ll use a real life scenario that is easy to identify with. Only a single rule is needed to test this condition:
If it is raining, an umbrella is needed.
import { evaluate } from 'regent';
// Rule(s)
const isRaining = { left: '@isRaining', fn: 'equals', right: true };
// Data
const data = { isRaining: true };
// Evaluation
const isUmbrellaNeeded = evaluate(isRaining, data); // true
Taking the previous example a bit further, we can refine the scenario to be more precise. We can create and combine multiple rules to test this condition:
If it is raining and the wind is calm, an umbrella is needed.
import { and, evaluate } from 'regent';
// Rule(s)
const isRaining = { left: '@isRaining', fn: 'equals', right: true };
const isCalm = { left: '@windSpeedInMph', fn: 'lessThan', right: 15 };
const isRainingAndCalm = and(isRaining, isCalm);
// Data
const data = { isRaining: true, windSpeedInMph: 20 };
// Evaluation
const isUmbrellaNeeded = evaluate(isRainingAndCalm, data); // false
Troubleshooting
When conditional logic becomes too complex (and it will), use Regent’s explain method to simplify the abstraction.
Documentation
Examples
- Basic Example
- Advanced Example: Weather
- Advanced Example: Batman
- Custom Predicate: Data Parsing
- Custom Predicate: Global Registration
- Custom Predicate: Query Argument
- Custom Predicate: With Lodash
- Composition with
and
- Composition with
and
(manual) - Composition with
not
- Composition with
or
- Composition with
xor
- Querying with
evaluate
- Querying with
explain
- Querying with
filter
- Querying with
find
License
MIT