json-logic-js
json-logic-js copied to clipboard
add 'some', 'all', 'none' operators
These new operators allow you to run tests on arrays of objects.
First argument is an array. Second is a logic object.
The logic object is run with a local scope of each item.
let data = {
cart: {
items: [{
qty: 2,
rate: 49.99,
sku: 'amno-90'
}, {
qty: 1,
rate: 144.99,
sku: 'nepr-300'
}, {
qty: 1,
rate: 129.99,
sku: 'synt-360'
}]
}
}
let someLogic = {
some: [
{var: 'cart.items'},
{
'===': [{var: 'sku'}, 'amno-90']
}
]
}
let allLogic = {
all: [
{var: 'cart.items'},
{
'>': [{var: 'qty'}, 0]
}
]
}
let noneLogic = {
none: [
{var: 'cart.items'},
{
'<': [{var: 'qty'}, 1]
}
]
}
console.log(jsonLogic.apply(someLogic, data)) // true
console.log(jsonLogic.apply(allLogic, data)) // true
console.log(jsonLogic.apply(noneLogic, data)) // true
Wow, my sincere apologies, I didn't understand what you were doing here until I opened the PR, and this is a really clever addition to the language.
Can you take a look at this branch and see if I'm hitting the same requirements you have? https://github.com/jwadhams/json-logic-js/tree/sets
Your test cases above pass, and I've got a dozen I'll be adding to the shared unit tests so I can port it to PHP and ping the Ruby implementer.
I changed your approach slightly because:
- We have a general rule for "first parameter isn't a rule" that it should be returned unevaluated so I wanted to expand
is_logic
rather than special casing empty object. - [].includes is not supported in any version of IE, so I rewrote it as a simple for loop that exits as early as possible.
Thanks again for your contribution!
Thanks @jwadhams, we are using these features in production right now.
I'm not sure what you are asking me to do here though.
Sorry, what I mean is: I'm about to roll these three operations into the standard JavaScript library.
They're in the shared unit tests, lines 291-414: https://github.com/jwadhams/json-logic/blob/gh-pages/tests.json
They're listed on the Operations page of the docs (with a disclaimer): http://jsonlogic.com/operations.html#all-none-and-some
But my implementation is slightly different from yours (to get IE compatibility mostly), and I wanted to make sure this makes your life better instead of worse. So for the moment it's checked into the main package with the tag 1.1.3-sets
or on NPM as json-logic-js@sets
. If you could test it out, I'd really appreciate it.