Operators & the Calculation Engine
30 min read
Implement the Equals Operation
Task
Use the stored state and calculation engine to implement =.
Open
Open:
js/calculator.js
Add equals() to the Calculator class.
Add the method
equals() {
const { previous, current, operation } = this.state;
if (previous === null || operation === null) {
return Number(current);
}
try {
const result = this.perform(previous, current, operation);
this.state.current = String(result);
this.state.lastExpression = `${previous} ${operation} ${current}`;
this.state.previous = null;
this.state.operation = null;
this.state.waitingForOperand = true;
this.state.justCalculated = true;
return result;
} catch (error) {
this.state.current = 'Error';
this.state.previous = null;
this.state.operation = null;
this.state.waitingForOperand = true;
this.state.justCalculated = true;
throw error;
}
}
The method coordinates the workflow but delegates arithmetic to perform().
Connect the operator and equals buttons
In js/ui.js, extend the existing button handler:
if (action === 'operation') {
calculator.chooseOperation(button.dataset.value);
}
if (action === 'equals') {
try {
calculator.equals();
} catch (error) {
console.error(error);
}
}
updateDisplay();
Use the action names already present in your starter markup if they differ.
Test
In the browser:
- Click
8. - Click
+. - Click
4. - Click
=. - Confirm the display shows
12.
Then test:
9 × 6 =→5420 − 7 =→1320 ÷ 5 =→4
Also test division by zero and confirm the application does not silently produce an incorrect result.
Checkpoint
The calculator can now perform its four basic arithmetic operations from the browser interface.