Refresh and check your calculator. All tests should pass at this point.
Improving calculate
We need to make sure firstValue and secondValue are numbers before we perform a calculation. Right now, we do this before we use calculate. We do this in both the operator and equal sections.
if (buttonType === 'operator') {
// ...
const firstValue = parseFloat(calculator.dataset.firstValue)
const operator = calculator.dataset.operator
const secondValue = parseFloat(result)
if (/*...*/) {
// Calculate goes here
}
}
if (buttonType === 'equal') {
const firstValue = parseFloat(calculator.dataset.firstValue)
const operator = calculator.dataset.operator
const modifierValue = parseFloat(calculator.dataset.modifierValue)
const secondValue = modifierValue || parseFloat(result)
if (/*...*/) {
// Calculate goes here here
}
}
If we use parsteFloat in calculate, we don’t have to use parseFloat in the operator and equal sections.
I tried reading the code from top to bottom. When I did this, I realised I get overwhelmed when I reached the clear section. This is normal because the code for operators and equal are quite complicated.
Since we can handle keys in any order, I choose to bring the clear key up in the hierarchy. When I do this, code becomes easier to read. I know the hard parts will come at the bottom.
If you think the clear key looks hard to read, you’re not alone. The order of operations doesn’t make sense to my brain. It goes like this right now:
if (buttonType === 'clear') {
// If clear key pressed twice, do this
// If clear key pressed at least once, do that
}
It’ll make more sense if we flip things around.
if (buttonType === 'clear') {
// If clear key pressed once, do this.
// If clear key pressed twice, do that.
}
First, we’ll bring up the display.textContent and button.textContent lines.
We use the variable result to signify the displayed value from the calculator.
const result = display.textContent
This can make things confusing because result usually signifies the result (after processing). We should use variable name like displayValue instead. displayValue is better because it describes the value it stores.
Let’s change all instances of result into displayValue. If you use Visual Studio Code, you can change all affected instances of a variable by pressing f2.
Now, when we make a calculation, we can use result instead of newResult. We’ll change all instances of newResult to result as well.
That’s it!
There’s is one more thing I’d like to refactor. But before that, we need to introduce the switch statement.