I'm currently writing a JS rule engine, which at some point should evaluate Boolean expressions using the eval () function.
First I will build the equation as such:
var equation = "relation.relatedTrigger.previousValue" + " " + relation.operator + " " + "relation.value";
the relation .relatedTrigger.previousValue is the value I want to compare.
relation.operator is an operator (either "==", "! =", <=, "<", ">",> = ").
the .value relation is the value I want to compare with.
Then I just pass this line to the eval function and return true or false as such:
return eval(equation);
This works absolutely fine (with words and numbers) or all operators except> = and <=. For instance. When evaluating the equation:
relation.relatedTrigger.previousValue <= 100
Returns true when previousValue = 0,1,10,100 and all negative numbers, but false for everything in between.
I would greatly appreciate the help of anyone who could answer my question or help me find an alternative solution.
Hi,
Ogier.
PS I do not need to talk about the uncertainty of the eval () function. Any value assigned to .relatedTrigger.previousValue is predefined.
edit: Here is the full function:
function evaluateRelation(relation) { console.log("Evaluating relation") var currentValue; //if multiple values if(relation.value.indexOf(";") != -1) { var values = relation.value.split(";"); for (x in values) { var equation = "relation.relatedTrigger.previousValue" + " " + relation.operator + " " + "values[x]"; currentValue = eval(equation); if (currentValue) return true; } return false; } //if single value else { //Evaluate the relation and get boolean var equation = "relation.relatedTrigger.previousValue" + " " + relation.operator + " " + "relation.value"; console.log("relation.relatedTrigger.previousValue " + relation.relatedTrigger.previousValue); console.log(equation); return eval(equation); } }
Answer: Provided by KennyTM below. String comparison does not work. A conversion to a number is required.