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

219
Views
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
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!