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

225
Vistas
Concatenate all numbers in an array, if it contains arithmetic signs

I have an input in which the format expression "2 * 42" || "4*2". I need to get the result of a given expression NOT using eval.

To solve this problem, I translated the expression into an array, but I ran into a problem that the numbers are not connected to each other, because I use split("").

Below I will attach my code, I solved the problem. But tell me please, how can I optimize this code?

const [ math, setMath ] = useState(null)
const [ value, setValue ] = useState('')

function handleButton(){
    let arr = value.split('').filter(elem => elem !== ' ')
    let arrValidate = [];
    let prev = '';
    for(let i = 0; i < arr.length; i++){
        if(i + 1=== arr.length){
            prev += arr[i]
            arrValidate.push(+prev)
        }
        if(!isNaN(+arr[i])){
            prev += arr[i]
        }else{
            arrValidate.push(+prev, arr[i])
            prev = ''
        }
    }
    switch(arrValidate[1]){
        case '+': {
            setMath(arrValidate[0] + arrValidate[2]);
            break;
        }
        case '-':{
            setMath(arrValidate[0] - arrValidate[2]);
            break;
        } 
        case '*':{ 
            setMath(arrValidate[0] * arrValidate[2]);
            break;
        }
        case '/': {
            setMath(arrValidate[0] / arrValidate[2]);
            break;
        }
    }
}

function handleInput(event) {
    setValue(event)
}

return <div>
    <p>{math}</p>
    <input value={value} onChange={event => handleInput(event.target.value)} />
    <button onClick={handleButton}>Click</button>

</div>
about 4 years ago · Juan Pablo Isaza
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