Operators & the Calculation Engine
20 min read
Store the Selected Operation
Task
Create a method that stores the current number and selected operator when an operation button is pressed.
Open
Open:
js/calculator.js
Add chooseOperation() inside the Calculator class.
Add the method
chooseOperation(operation) {
if (this.state.current === '' || this.state.current === null) {
return;
}
if (this.state.previous !== null && this.state.operation) {
this.equals();
}
this.state.previous = this.state.current;
this.state.operation = operation;
this.state.waitingForOperand = true;
this.state.justCalculated = false;
}
The previous value records the first operand. The operation value records what should happen when the second operand arrives.
Test
Run:
calculator.clear();
calculator.inputDigit('8');
calculator.chooseOperation('+');
calculator.state;
Confirm that:
previousis"8"operationis"+"waitingForOperandistrue
Checkpoint
The calculator now remembers the first operand and the operation selected by the user.