Question presented to candidate:
"Build a basic calculator like the one on a phone: digits, a decimal point, plus, minus, times, divide, equals, clear and backspace. It should respect operator precedence, so 12 + 3 ร 4 is 24, and it must not use eval. Make the keyboard work too."
Requirements:
- Buttons for 0 to 9,
.,+ โ ร รท,=, AC (clear all) and โซ (backspace); the display shows the expression as it is typed. =evaluates with normal precedence (ร and รท before + and โ), withoutevalornew Function.- Pressing an operator right after another replaces it; a number can have only one decimal point; leading zeros are dropped; a leading minus makes a negative number.
- After
=, an operator continues from the result and a digit starts a new calculation. - Division by zero shows an error; the next key starts over.
- Results display cleanly: 0.1 + 0.2 shows 0.3.
- Physical keyboard support: digits, operators, Enter, Backspace, Escape.
What a strong answer should cover:
- Separating the pure logic (a key-press reducer, a tokenizer, a parser) from the UI.
- Why
evalis unsafe and how a small recursive-descent parser (or shunting-yard) handles precedence. - Floating-point representation (
0.1 + 0.2 === 0.30000000000000004) and rounding for display, plus overflow and tiny numbers. - The input state machine: what each key does after a result, after an error, after an operator.
- Keyboard handling with a window listener that is cleaned up, and
preventDefaultso Enter does not also click a focused button. - Accessibility: named operator buttons, a live display.
Clarifying questions expected:
- "Immediate execution like a basic pocket calculator (12 + 3 ร 4 = 60), or precedence like a phone (24)?"
- "Do we need parentheses, percent or memory keys?"
- "How many digits can the display show?"
Code / implementation expected: Yes. A working calculator with a separate, testable evaluator that does not use eval.