Hi all! I’m building a react calculator for the frontend libraries projects, and I’m a bit stuck now trying to evaluate the results.
I made long time ago one with eval, but I’m trying a different approach now, generating an array of numbers and strings for the signs, which I will care of at the end.
Meanwhile the user inputs the numbers I parse them with this function:
parseData: function (arr, value) {
//numbers
if (!this.isOp.test(value)) {
value = parseFloat(parseFloat(value).toFixed(4))
if (arr.at(-1) === '-') {
value = -value
arr = [...arr.slice(0, -1)]
}
}
//return signs or numbers already parsed
return (arr= [...arr, value])
},
I invoke this function in this way:
setFormula(run.parseData(formula, currentVal))
where run
is the object where I store all the helper functions.
formula= state to store all inputs.
currentVal = state to store the last input.
Until here is all fine, my problem is when I invoke this function at the end to parse the last result when the user clicks ‘=’.
from the same object:
calculate: function (arr, value) {
this.parseData(arr, value)
this.evalLastInput(arr).filter(item => item !== '+').this.calcPrecedence(arr)
return setResult(arr)
},
I always get the same Array without change. I put some console logs and the array is actually changing, but when it returns is the same again.
I tryed to re declare it before sinding to next function, but the same result, I guess is referencing always the same arr, but how can I change this array between functions?
What I want to do is:
receive an array in my function as argument then → send to anothe and get back again changed, then to another 2 functions.
I can write all functions inside the same but the problem is with the first which is being used more often for other components.