I am trying to convert a string representation of an operator to the operator itself in comparisons.
For example, something like
{obj1} '==' {obj2}
should be:
{obj1} == {obj2}
OR
{obj1} '!==' {obj2}
should be:
{obj1} !== {obj2}
I can use eval(), but that forces the objects to be compared to be converted to a string, causing === (strict type check) comparisons useless.
For example, in the following example, eval would give wrong results:
const obj = "5"
const obj2 = 5
const operator = '===';
eval(`console.log(${obj} ${operator} ${obj2})`) //outputs true, incorrect (obj is of type string, obj2 is of type number)
console.log(obj === obj2) //outputs false, correct
How should I approach this?
Possible approach
One way that I came up with is just to go through the if else ladder and let js handle the comparison instead of parsing the comparison operator.
Something like
if(condition === '!=='){
return before_OrderRequest.Id !== after_OrderRequest.Id
}else if (condition === '==='){
return before_OrderRequest.Id === after_OrderRequest.Id
}
//...more if statements
eval()is falling short of our requirement, or maybe there is a way to just eval the condition operator that I don't know of, please explain.eval()