Katkat

Build a Stateful Calculator

ZooxFrontend Engineer · Onsite

Last updated

This question tests the ability to manage complex state transitions in a UI component, specifically handling input sequences, operator precedence, and state consistency in a stateful calculator.

Stateful Calculator Implementation

Your task is to implement the core logic for a stateful calculator that supports basic arithmetic operations (+, -, *, /). Unlike a simple calculator, this one must handle operator chaining and state transitions effectively.

Requirements

  1. Input Handling: The calculator should accept numeric digits, operators, and a 'clear' command.
  2. State Management: Keep track of the current value being entered, the previous operand, and the pending operator.
  3. Operator Chaining: If a user enters '5 + 5 +', the calculator should immediately resolve the first addition (displaying 10) before waiting for the next input.
  4. Interface: Implement a class or function that exposes press(key) and returns the current display value as a string.

Example Flow

  • press('5') -> display "5"
  • press('+') -> display "5"
  • press('5') -> display "5"
  • press('+') -> display "10" (resolves 5+5, prepares for next operation)
  • press('2') -> display "2"
  • press('=') -> display "12" (resolves 10+2)

Constraints

  • Handle division by zero by returning "Error".
  • The input is provided as a sequence of strings (digits or operators).
  • Ensure that multiple operator presses (e.g., '5 + + 5') do not crash the application (overwrite the operator).
class Calculator:
    def __init__(self):
        pass

    def press(self, key: str) -> str:
        # Implementation here
        pass

Hints

Hint 1

Define a finite state machine with states such as 'awaiting_operand', 'awaiting_operator', and 'result_displayed'.

Hint 2

Store the 'previous_value', 'current_value', and 'pending_operator' as properties of your class.

Hint 3

Use a helper function to perform the actual arithmetic so that logic remains isolated from the state transition logic.

Follow-up questions

  • How would you modify your implementation to support a decimal point key?
  • How would you implement a 'history' feature that allows the user to see the last five calculations?
  • How would you ensure the calculator remains responsive and consistent if the logic was moved to a web worker to prevent UI jank?