Calculation History
20 min read
Create History State
Task
Add a history collection to the calculator state.
Open
Open:
js/calculator.js
Add history to the state created in the constructor.
history: []
Then add a method for creating a history item:
addHistory() {
const { lastExpression, current } = this.state;
if (!lastExpression || current === 'Error') {
return;
}
this.state.history.unshift({
expression: lastExpression,
result: current,
timestamp: Date.now()
});
}
Use unshift() so the newest calculation appears first.
Update equals
At the end of a successful equals() calculation, call:
this.addHistory();
Place it after lastExpression and current have been updated.
Test
Run:
calculator.clear();
calculator.inputDigit('8');
calculator.chooseOperation('+');
calculator.inputDigit('2');
calculator.equals();
calculator.state.history;
You should see one history item containing the expression, result, and timestamp.
Checkpoint
Completed calculations are now stored in application state.