JavaScript Snippet

Generators as State Machines

Difficulty: Hard

Generators turn an explicit `switch (state)` block into a function whose own pause points encode the state. This snippet shows three flavors: a finite-state machine driven by `next(event)` for transitions, a step-by-step async sequencer that pauses between phases, and a richer machine with entry/exit side effects plus an unexpected-event handler. Reach for this when your control flow has a small, explicit set of states and you want the language to enforce them for you.