Verdict is a lightweight, single file, extensible JavaScript library for evaluating complex conditions against data objects. It uses a syntax similar to MongoDB’s query language, allowing you to perform comparisons, logical operations, and even arithmetic evaluations in a clear, declarative way.
- Field-based Conditions: Access nested properties using dot notation.
- Comparators: Support for
$eq
,$ne
,$gt
,$gte
,$lt
,$lte
,$in
,$nin
,$contains
. - Logical Operators: Combine conditions using
$and
,$or
, and$not
. - Arithmetic Expressions: Evaluate expressions with
$add
,$subtract
,$multiply
,$divide
,$mod
,$exp
. - Extensible: Easily add custom comparators, logical operators, and arithmetic operators.
- Robust Error Handling: Clear error messages for invalid conditions or expressions.
Just copy one file: Verdict.js in your project and start using as show below.
const Verdict = require('./Verdict');
const executor = new Verdict();
const data = {
metadata: {
user_plan: "paid",
user_age: 25,
name: "John Doe"
},
stats: {
score: 85
}
};
const condition = {
"$and": [
{ "metadata.user_age": { "$gt": 18 } },
{ "stats.score": { "$gte": 80 } }
]
};
const result = executor.evaluate(data, condition);
console.log(result); // Output: true
const condition = {
"stats.score": {
"$gt": {
"$add": [50, 30]
}
}
};
console.log(executor.evaluate(data, condition)); // Output: true
executor.addComparator('$between', (value, range) => {
if (!Array.isArray(range) || range.length !== 2) {
throw new Error('$between operator requires an array with exactly two elements.');
}
return value >= range[0] && value <= range[1];
});
const betweenCondition = {
"metadata.user_age": { "$between": [20, 30] }
};
console.log(executor.evaluate(data, betweenCondition)); // Output: true
// Add a $square operator that squares a single operand.
executor.addArithmeticOperator('$square', (a) => a * a);
const expr = { "$square": [5] };
console.log(executor.evaluateExpression(expr)); // Output: 25
Check out Verdict.test.js
This project uses Jest for testing. To run the tests:
-
Clone the repository.
-
Install the dependencies:
npm install
-
Run the tests:
npm test
Contributions, feedback, and feature requests are welcome! Feel free to fork the repository, submit pull requests, or open issues to help the project improve.
This project is licensed under the MIT License. See the LICENSE file for more details.