KatInterview

Design a Phone-Style Calculator in the Browser

Data Structure DesignModel answer
MediumModel answerData Structure Designstate-machinefrontendjavascript

Last updated

Build a four-function calculator UI with immediate-execution semantics, tricky key sequences handled correctly, and a layout close to a familiar mobile calculator.

Task

Build a working calculator in the browser that behaves and looks like a standard phone calculator. Use plain HTML/CSS/JS or a framework such as React. Math-expression or calculator libraries are not allowed.

Layout

  • A display at the top, right-aligned, showing 0 initially.
  • A button grid below it containing:
    • digits 0–9 and a decimal point .
    • operators +, −, ×, ÷
    • equals =
    • AC (reset), +/− (sign toggle), % (percent)
  • Operators sit in their own visually distinct column, and the display text shrinks when the number gets long.

Required behavior

  • Digits build up the current number. An operator stores it as the pending operation, and = applies the pending operation.
  • Evaluation is immediate, left to right, with no operator precedence. 2 + 3 × 4 = gives 20, and intermediate results appear as soon as the next operator is pressed.
  • Pressing two operators in a row replaces the first one rather than computing anything.
  • Pressing = repeatedly repeats the last operation. For example, 2 + 3 = = gives 8.
  • A digit typed right after = starts a new number.
  • Only one . is allowed per number, and leading zeros are not accumulated (007 shows 7).
  • ÷ 0 shows Error. Only AC, a digit or . leaves the error state.
  • % divides the current number by 100.
  • +/− toggles the sign. Right after an operator it shows -0 and starts a new operand.
  • Floating-point noise must not reach the display, so 0.1 + 0.2 = shows 0.3. Input is capped at 9 digits, and results are rounded to 12 significant digits, falling back to exponential notation if still too long.
  • AC restores the initial state.

What is expected

Describe your design and assumptions as you go, implement the calculator, and walk through the awkward key sequences above to show they work. Your answer will be judged on correctness, code structure and naming, edge-case handling, and visual closeness to a typical phone calculator.

Hints

Hint 1

Keep the logic in a pure function reduce(state, key) that returns a new state, and let the UI only render state.display and forward clicks. Store the display as a string so '0.' and '-0' are representable.

Hint 2

You need a flag meaning 'the next digit starts a new number' (set after an operator or '='). That one flag explains operator replacement, chaining, and typing after '='. Also remember the last operator and operand so a second '=' can repeat them.

Hint 3

Round every computed result with toPrecision(12) and convert back with Number(...) to remove 0.1 + 0.2 noise, and normalize -0 to 0. Treat division by zero (a non-finite result) as the Error state.