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>