Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
Concatenar todos los números en una matriz, si contiene signos aritméticos

Tengo una entrada en la que la expresión de formato "2 * 42" || "4*2". Necesito obtener el resultado de una expresión dada NO usando eval.

Para resolver este problema, traduje la expresión a una matriz, pero me encontré con el problema de que los números no están conectados entre sí, porque uso split("").

A continuación adjuntaré mi código, resolví el problema. Pero dime por favor, ¿cómo puedo optimizar este código?

 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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!