• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

169
Vistas
Invertir una operación matemática de + a -

Quiero convertir una operación matemática en Javascript. Por ejemplo, dado un "-", debería convertirse en "+", "*" - "/" y así sucesivamente.

Mi código actual es un caso de cambio, que es muy lento de realizar:

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

¿Hay una solución mejor/más rápida para este problema?

about 3 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

El rendimiento será insignificante, pero para las operaciones que asignan una cosa a otra cosa, un enfoque basado en tablas suele ser más fácil de mantener a largo plazo:

 const inverseOperations = { '+': '-', '-': '+', '/': '*', '*': '/', }; if (contents.className == "buttonfunction") { const operation = contents.innerHTML if (invert == true && inverseOperations[operation]) { contents.innerHTML = inverseOperations[operation]; } document.body.appendChild(contents); }
about 3 years ago · Santiago Trujillo Denunciar

0

Agregué algo de contexto para hacer un ejemplo en ejecución.

Por cierto, el enfoque utilizado aquí es un mapa de reglas para la inversión, reemplazando la lógica que estaba usando en su declaración de cambio:

 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 3 years ago · Santiago Trujillo 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda