I want to code a function to handle definable conditions.
The reference data is contained in an object and a simple condition is stored in a 3 elements array like this :
["name", "==", "John Doe"]
here is the code that works well to test a simple condition:
function getResultOfSimpleCondition(data, condition) {
let c1 = data[condition[0]],
operateur = condition[1],
c2 = condition[2], cond=true;
switch(operateur){
case "==" :
case "=" : cond = (c1 == c2 ); break;
case "!=" : cond = (c1 != c2 ); break;
case ">" : cond = (c1 > c2 ); break;
case "<" : cond = (c1 < c2 ); break;
case ">=" : cond = (c1 >= c2 ); break;
case "<=" : cond = (c1 <= c2 ); break;
case "like": cond = (c1.indexOf(c2) > -1); break;
case "not like": cond = (c1.indexOf(c2) == -1); break;
default : cond = (c1 == c2 ); break;
}
return cond
}
let myData = { name:'John Doe', age:'28', town:'PARIS', qty:5, uptodate: true},
condition_0 = ["name", "==", "Jack Sparrow"], // result false
condition_1 = ["age", ">=", "24"], // result true
condition_2 = ["uptodate", "==", false], // result false
condition_3 = ["town", "==", "PARIS"]; // result true
console.log( getResultOfSimpleCondition(myData, condition_0) )
what I’m looking for is how to implement more complex conditions on the same principle.
For example:
on 2 levels:
[ condition_0, "OR", condition_1 ]
// result true
or
[ condition_1, "AND", condition_2 ]
// result false
on more levels:
[[ condition_0, "OR", condition_1 ], "AND", condition_3]
// result true
or
[[ condition_0, "OR", condition_1 ], "AND", condition_3, "AND NOT", [condition_5, "OR", condition_23 ] ]
thank you in advance