Hi everybody
So, trying to do the calculator project with React, and I have one main question and one bug I can’t resolve, would love your feedback.
First, the question - I went with “formulaic logic” by using eval() to do the actual calculation. I saw that even the FCC example calculator does that, even though it’s recommended in the docs to avoid eval().
I suppose it is possible to do an immediate-logic calculator, but in React, wouldn’t that involve saving way too much states (you would need, at the very least, one for the saved number (or current result), and one for the current operator. I also have a state for whether a number already has a decimal in it.
Wouldn’t it get really messy real quick? Is that the learning point of this exercise?
And, for my bug, it’s with test 13 (two or more operators). I got a few lines of codes going that are supposed to correct this, but for some reason, the rendered display becomes a number rather than a string (despite my many attempt to toString() it), and then I get an exception on the second calculation.
Here are the relevant lines:
// if last char in display is operator
// if (isOperator(display.charAt(display.length - 1)) && op !== "-") {
// const updatedDisplayStr = display.slice(0, display.length - 1)
// .concat(op);
// setDisplay(updatedDisplayStr);
// };
The problem is that “display.charAt is not a funciton”, since for some reason, display (the variable in state) becomes a number, despite my attempts to toString() it.
And these are found in the handleOperator function (a designated function to handle operations).
The full code is here:
Would love any input on this. Calculators aren’t as simple as they seem to be!
Thanks!