Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda