Skip to the solution
HardLow-Level Design6 min read

Build a Minimal State Machine Runner (States, Transitions, Guards)

482 views

The problem

Problem, as an interviewer would state it: "Build a minimal finite state machine runner: given a config of states and their allowed transitions, send(event) should move to the next state — but only if an optional GUARD function, checking real context data, allows it."

Examples:

Code
const machine = createMachine({ initial: "red", states: {...} });
machine.send("TIMER"); // transitions if a matching, allowed transition exists

Clarifying questions expected:

  • What should happen when send is called with an event that has NO matching transition from the current state?
  • Should a guard function receive the machine's own context data, to make a real, informed decision?
  • Does the machine need to support entry/exit actions (side effects run on entering/leaving a state), or just the pure transition logic?

Code / implementation expected: Yes — real, direct proof through a real, multi-step traffic-light sequence: correct transitions on valid events, a guard genuinely blocking one specific transition, and an unhandled event correctly leaving the state unchanged.

  • state-machine
  • system-design

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a traffic-light state machine correctly transitions, a guard genuinely blocks one transition, and an unhandled event leaves state unchanged

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 152 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Implement a Drag-and-Drop List Reordering Utility Without a Library

Continue