Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
JavaScript convert string to operator

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
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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))

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda