Design a Phone-Style Calculator in the Browser
Data Structure DesignModel answerLast 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
0initially. - A button grid below it containing:
- digits
0–9and a decimal point. - operators
+,−,×,÷ - equals
= AC(reset),+/−(sign toggle),%(percent)
- digits
- 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 =gives20, 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 = =gives8. - A digit typed right after
=starts a new number. - Only one
.is allowed per number, and leading zeros are not accumulated (007shows7). ÷ 0showsError. OnlyAC, a digit or.leaves the error state.%divides the current number by 100.+/−toggles the sign. Right after an operator it shows-0and starts a new operand.- Floating-point noise must not reach the display, so
0.1 + 0.2 =shows0.3. Input is capped at 9 digits, and results are rounded to 12 significant digits, falling back to exponential notation if still too long. ACrestores 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Most of the difficulty is in the awkward sequences, not in addition, so I would model the calculator as a small state machine with all logic separated from the DOM.
First I would state my assumptions aloud: immediate execution, repeated = repeats the last operation, ÷ 0 gives Error, input is capped at 9 digits, and results are rounded to 12 significant digits.
State
| Field | Meaning |
|---|---|
display | String being shown or edited. A string keeps "0." and "-0" intact. |
acc | Left operand (number), or null. |
pending | Operator waiting for a right operand, or null. |
fresh | If true, the next digit or . starts a new operand. |
repeatOp, repeatArg | Saved after = so another = can repeat the operation. |
The transition function is reduce(state, key) -> state. The UI is a thin shell: on click it calls reduce, then renders.
Transition rules
- Digit: if
fresh, replace the display. If the display is0or-0, replace the zero. If it already has 9 digits, ignore the key. Otherwise append. .: iffresh, start"0.". If the display already contains a dot, ignore it. Otherwise append.- Operator:
- If an operator is pending and
freshis false, a second operand was typed. Computeacc pending display, show the result, and make it the newacc. - If
freshis true, nothing new was typed, so just swap the pending operator. - Either way, set
pending = keyandfresh = true.
- If an operator is pending and
=: if an operator is pending, apply it. Otherwise, if there is a saved repeat operation, apply that to the display. Store the repeat data, clearpending, and setfresh = true.+/−: right after an operator, show-0and start an operand. Otherwise flip the leading minus sign.%: divide the display value by 100.AC: return the initial state.- Error: ignore everything except
AC, a digit or..
Test sequences I would run
| Keys | Expected |
|---|---|
2 + 3 + 4 = | 5 after the second +, then 9 |
2 + × 3 = | 6 (operator replaced) |
2 + 3 = = | 8 |
2 + 3 = 7 | 7 |
1 . . 5 | 1.5 |
0 0 7 | 7 |
5 ÷ 0 = | Error |
0.1 + 0.2 = | 0.3 |
50 + 10 % = | 50.1 |
Code
// engine.js - pure logic, no DOM
const MAX_INPUT_DIGITS = 9;
export const INITIAL = Object.freeze({
display: "0", acc: null, pending: null, fresh: true,
repeatOp: null, repeatArg: null,
});
const ERROR_STATE = Object.freeze({ ...INITIAL, display: "Error" });
const OPS = {
"+": (a, b) => a + b,
"−": (a, b) => a - b,
"×": (a, b) => a * b,
"÷": (a, b) => (b === 0 ? NaN : a / b),
};
const digitCount = (s) => s.replace(/[-.]/g, "").length;
function fmt(n) {
if (!Number.isFinite(n)) return "Error";
const r = Number(n.toPrecision(12)) || 0; // drops float noise and -0
const s = String(r);
return digitCount(s) > 12 ? r.toExponential(6) : s;
}
export function reduce(state, key) {
if (key === "AC") return INITIAL;
const isError = state.display === "Error";
if (isError && !/^[0-9.]$/.test(key)) return state;
const s = isError ? INITIAL : state;
if (/^[0-9]$/.test(key)) {
if (s.fresh) return { ...s, display: key, fresh: false };
if (s.display === "0") return { ...s, display: key };
if (s.display === "-0") return { ...s, display: "-" + key };
if (digitCount(s.display) >= MAX_INPUT_DIGITS) return s;
return { ...s, display: s.display + key };
}
if (key === ".") {
if (s.fresh) return { ...s, display: "0.", fresh: false };
if (s.display.includes(".")) return s;
return { ...s, display: s.display + "." };
}
if (key in OPS) {
if (s.pending && !s.fresh) {
const shown = fmt(OPS[s.pending](s.acc, Number(s.display)));
if (shown === "Error") return ERROR_STATE;
return { ...s, display: shown, acc: Number(shown), pending: key, fresh: true };
}
const acc = s.pending ? s.acc : Number(s.display);
return { ...s, acc, pending: key, fresh: true };
}
if (key === "=") {
let left, op, right;
if (s.pending) { left = s.acc; op = s.pending; right = Number(s.display); }
else if (s.repeatOp) { left = Number(s.display); op = s.repeatOp; right = s.repeatArg; }
else return { ...s, fresh: true };
const shown = fmt(OPS[op](left, right));
if (shown === "Error") return ERROR_STATE;
return { ...s, display: shown, acc: null, pending: null, fresh: true,
repeatOp: op, repeatArg: right };
}
if (key === "+/−") {
if (s.fresh && s.pending) return { ...s, display: "-0", fresh: false };
const d = s.display.startsWith("-") ? s.display.slice(1) : "-" + s.display;
return { ...s, display: d };
}
if (key === "%") {
return { ...s, display: fmt(Number(s.display) / 100), fresh: false };
}
return s;
}
The UI uses one click listener on the button container (event delegation) that calls state = reduce(state, button.dataset.key) and then renders. Rendering sets display.textContent, shrinks the font size when the string is longer than about 7 characters, and highlights the pending operator button while fresh is true.
Styling notes
- Wrap the keys in a CSS grid with 4 equal columns, and make
0span two columns. - Use a dark background, round buttons, and a system sans-serif font with a light weight for the display.
- Give the operator column an accent color, the
AC,+/−and%keys a lighter gray, and the digits a darker gray. - Use
:activeto dim the buttons on press.
Complexity
Each key press is O(1) in time and space, since strings are capped at about 12 characters and the state has a fixed size.
Trade-offs and common mistakes
- Reading numbers back from the DOM: this makes
0.and-0fragile and hard to test. Keep explicit state. - Using
evalor a string expression: this gives precedence semantics and hides the intermediate results the spec requires. - Forgetting the replace-operator case:
2 + × 3then computes with a bogus operand. - Showing raw floats: always round with
toPrecision. For exact decimal arithmetic you would use scaled integers or a decimal library, but that is overkill here. - Mutating state in place: returning new objects makes the engine trivially unit-testable and works well with React.
Follow-ups to be ready for
- Keyboard support: map keys such as
*to×andEnterto=, and call the samereduce. - Operator precedence: switch to a two-stack (shunting-yard style) evaluator and add parentheses.
- Accessibility: use real
<button>elements, anaria-live="polite"display, and visible focus styles. - Testing: table-driven tests of key sequences against the engine, plus one or two DOM smoke tests.