Code Snippets
/

Generators as State Machines

Generators as State Machines

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.

JavaScript
Hard
generators
state-machine
control-flow

1,099 views

26

function* doorMachine() {
    let state = 'closed';
    while (true) {
        const event = yield state;
        if (state === 'closed' && event === 'open') state = 'open';
        else if (state === 'open' && event === 'close') state = 'closed';
        else if (state === 'closed' && event === 'lock') state = 'locked';
        else if (state === 'locked' && event === 'unlock') state = 'closed';
        // Any other (state, event) pair is ignored: the door simply stays put.
    }
}

const door = doorMachine();
console.log(door.next().value);         // 'closed'  (initial pull, no event)
console.log(door.next('open').value);   // 'open'
console.log(door.next('lock').value);   // 'open'    (lock ignored from open)
console.log(door.next('close').value);  // 'closed'
console.log(door.next('lock').value);   // 'locked'
console.log(door.next('open').value);   // 'locked'  (open ignored from locked)
console.log(door.next('unlock').value); // 'closed'

A function* generator pauses at every yield, which makes it a natural fit for a state machine: the body is the code that runs on each transition, and the yield expression is where the next event arrives. The first call to next() runs the function up to the first yield and returns the initial state, so the argument passed to that very first next() is discarded by design. Subsequent next(event) calls resume the generator with event as the value of the previous yield, evaluate the transition rules, and pause again. Invalid (state, event) pairs fall through silently in this minimal version, which is often what you want for hardware-style devices that should not crash on noise.

2 more snippets in this entry are available for premium members.

Upgrade to Premium