ILILCode
HomeJavaScriptProjectsproject

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.

The state
{
  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
}
  1. 01Calculate — one function, four operators, and an error for anything unknown.
  2. 02Press — a reducer that takes the state and a key and returns the next state.
  3. 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 Error with the message Cannot 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. Set fresh: false.
  • operator (+ - * /) — store Number(display) in stored, save op, set fresh: true.
  • `=` — compute stored op display. Write the result into display as a string and reset stored, op to null and fresh to true. 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