Number Input & Display Logic
20 min read
Handle Number Input
Task
Make the calculator accept a digit and store it in state.current.
Open
Open:
js/calculator.js
Add an inputDigit() method inside the Calculator class.
Add the method
inputDigit(digit) {
if (this.state.waitingForOperand || this.state.justCalculated) {
this.state.current = digit;
this.state.waitingForOperand = false;
this.state.justCalculated = false;
return;
}
if (this.state.current === '0') {
this.state.current = digit;
return;
}
this.state.current += digit;
}
This method handles three cases:
- A new operand is expected, so the digit replaces the current value.
- The calculator is showing its initial
0, so the digit replaces it. - Otherwise, the digit is appended to the current value.
Test
In the browser console, try:
calculator.clear();
calculator.inputDigit('5');
calculator.inputDigit('2');
calculator.state.current;
The result should be:
"52"
Then test a new operand:
calculator.state.waitingForOperand = true;
calculator.inputDigit('8');
calculator.state.current;
The result should be:
"8"
Checkpoint
The calculator can now build multi-digit numbers from individual digit inputs.