Home > Back-end >  JavaScript convert string to operator
JavaScript convert string to operator

Time:09-16

I am trying to convert a string representation of a 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 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

CodePudding user response:

You can define an object with the string representation of operators as properties that return an arrow function performing the corresponding comparison.

const compare = {
  '==': (a, b) => a == b,
  '!=': (a, b) => a != b,
  '===' : (a, b) => a === b,
  '!==' : (a, b) => a !== b
}

const obj1 = 1;
const obj2 = 2;

console.log(compare['=='](obj1, obj2))
console.log(compare['!='](obj1, obj2))
console.log(compare['==='](obj1, obj2))
console.log(compare['!=='](obj1, obj2))

  • Related