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

218
Visualizações
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 à 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