Check conditional statements and return true/false
npm i @flipbyte/when-condition
Define your conditionals using an array with logical rule ('and' or 'or') as the first element followed by an array of comparison conditions.
General representation of a logical rule is as follows:
['{your logical rule}', [{your comparison rule 1}], [{your comparison rule 2}], ...]
Comparison rule is an array with 3 elements:
- The comparison rule.
- The key of the object whose value needs to be compared with a condition.
- The comparison value.
General representation of a comparison rule is as follows:
['{comparison rule}', '{key}', '{comparison value}']
Consider an object as follows:
let data = {
a: 1,
b: 2,
c: {
d: 'string',
e: [{
f: 1,
g: 2
}]
}
}
let rule = ['is', 'a', 1]
or
let rule = ['is', 'c.e[0]`.f', 1]
let rule = ['and', ['is', 'a', 1], ['is', 'b', 2]]
let rule = ['or', ['is', 'a', 1], ['is', 'b', 2]]
let rule = ['or', ['and', ['is', 'a', 1], ['is', 'b', 2]], ['and', ['is', 'b', 2], ['is', 'c.d', 'string']]]
import when from 'when-condition'
when(rule, data) // => returns true or false
You can also pass a callback function to check the data. Which will be resolved to a promise. It can either be a plain function or a promise
when(function(data) {
return data.a !== data.b
}, data).then((result) => {
//...handle your result
})
There are 2 types of logical rules:
and
- checks whether all the conditions evaluate to true.or
- checks whether atleast one condition evaluates to true.not
- returns the opposite of the evaluated comparison rule. This logical rule takes only one comparison rule.
Following are the available comparison rules:
is
- returns true if the object value strictly matches the comparison value.isOfType
- returns true if the object value matches the specified type (Ex: string, undefined, etc.).anyOf
- returns true if at least one of the comparison values matches the object key value. The comparison value needs to be an array.allOf
- returns true if all the object key value matches the comparison values. The comparison value needs to be an array.gt
- returns true if the object key value is greater than the comparison valuegte
- returns true if the object key value is greater than or equal to the comparison valuelt
- returns true if the object key value is lesser than the comparison valuelte
- returns true if the object key value is lesser than or equal to the comparison value
The MIT License (MIT)