Project: Calculator
Turn a string of button presses into state — the reducer pattern in miniature.
Project 23 of 23 in JavaScript30 min2 exercises
A calculator is a state machine with a tiny vocabulary: digits, four operators, equals, clear. Every button press produces the next state. Keep that function pure and the UI becomes a thin shell.
{
display: "0", // what the screen shows, always a string
stored: null, // the number waiting for an operator
op: null, // "+", "-", "*", "/" or null
fresh: true // true when the next digit starts a new number
}- 01Calculate — one function, four operators, and an error for anything unknown.
- 02Press — a reducer that takes the state and a key and returns the next state.
- 03In the full app: render the display, map buttons to keys, and keep the state in one variable.
Exercises
Checked in your browser · hints and solutions included
01
Exercise
Checkpoint 1 — calculate
Write calculate(a, op, b) that supports +, -, * and /.
- dividing by zero throws an
Errorwith the messageCannot divide by zero - an unknown operator throws an
Error(any message) - everything else returns the number
exercise.js
console · run your code or check the answer
02
Exercise
Checkpoint 2 — press a key
Write press(state, key) that returns the next state and never mutates the old one.
- digit — if
fresh, the digit replaces the display; otherwise append it. Setfresh: false. - operator (
+ - * /) — storeNumber(display)instored, saveop, setfresh: true. - `=` — compute
stored op display. Write the result intodisplayas a string and resetstored,optonullandfreshtotrue. If the result is not finite, show"Error". - `C` — back to
{ display: "0", stored: null, op: null, fresh: true }. - anything else — return the state unchanged.
The compute helper is already written for you.
exercise.js
console · run your code or check the answer