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

231
Visualizações
Inverting a math operation from + to -

I want to convert a math operation in Javascript. For example given a "-", it should get converted to a "+", "*" - "/" and so on.

My current code is a switch case, which is really slow to perform:

if (contents.className == "buttonfunction") {
                if (invert == true) {
                    switch (contents.innerHTML) {
                        case "+":
                            contents.innerHTML = "-";
                            break;
                        case "-":
                            contents.innerHTML = "+";
                            break;
                        case "*":
                            contents.innerHTML = "/";
                            break;
                        case "/":
                            contents.innerHTML = "*";
                            break;
                    }
                } 
                document.body.appendChild(contents);
            }

Is there a better/faster solution to this problem?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Performance will be negligible but for operations that map a thing to another thing, a table-driven approach is often more maintainable in the long run:

const inverseOperations = {
 '+': '-',
 '-': '+',
 '/': '*',
 '*': '/',
};

if (contents.className == "buttonfunction") {
  const operation = contents.innerHTML
  if (invert == true && inverseOperations[operation]) {
    contents.innerHTML = inverseOperations[operation];
  }
  document.body.appendChild(contents);
}
 
about 4 years ago · Santiago Trujillo Relatório

0

I added some context to make a running example.

By the way the approach used here is a map of rules for inversion, replacing the logic you were using in your switch statement:

let invert = true;

//granular map of pairs declaring the inverse of each operator
//it could be declared inline here but it could be also fed with the addInversionInMap
let inverted = {}; //{ '+' : '-', '-' : '+', '*' : '/', '/' : '*'}

addInversionInMap('+','-');
addInversionInMap('*','/');
//feeds the inverted map without repeating the both the sides in declaration
function addInversionInMap(op, opInverted){  
  inverted[op] = opInverted;
  inverted[opInverted] = op;  
}

//on document ready adds the click handler to every .buttonfunction elements
document.addEventListener("DOMContentLoaded", function() {
  addClickHandlerToButtonsFunction();
});

//adds the handler for click event on .buttonfunction
function addClickHandlerToButtonsFunction(){
  let btns = Object.values(document.getElementsByClassName('buttonfunction'));
  for(let btn of btns){
    btn.addEventListener('click', invertValue);
   }
}

//return the inverted operator based on the inverted map
//(or return the operator as is if there's no way to invert)
function getInvert(operator){
  if(inverted.hasOwnProperty(operator))
    return inverted[operator];
  else
    return operator;
}

//inverts the value of the element whose id is declared in the data-target attribvute
//of the button that triggered the click event (such element should be input type text)
function invertValue(){
  let contents = window.event.target;
  if (contents.className == "buttonfunction") {
    if (invert == true) {   
      let targetId = contents.getAttribute('data-target');
      let target = document.getElementById(targetId);
      //I'm using value so I expect the element to be input type text
      target.value = getInvert(target.value);
    }    
  }
}
button.buttonfunction{
  cursor: pointer;
}
<input id="input" type="text"></input>
<button type="button" class="buttonfunction" data-target="input">Invert</button>

about 4 years ago · Santiago Trujillo 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