JavaScriptFundamental (ES6), part 2
State machine with a generator in JavaScript
6 A generator as a state machine
hardModel an order's lifecycle as a generator. Each next(event) sends an event in and yields the new state; an event the current state cannot handle is ignored; reaching a terminal state ends the generator and returns the full history.
Stuck? Three hints, smallest first
- 1. Keep the transitions as data: state -> event -> next state. The generator only walks the table.
- 2.
continueafter an unrecognised event, so the same state is yielded again. - 3. A state with no outgoing transitions is terminal, which is the loop condition.
const TRANSITIONS = {
pending: { pay: 'paid', cancel: 'cancelled' },
paid: { ship: 'shipped', refund: 'refunded' },
shipped: { deliver: 'delivered' },
cancelled: {},
refunded: {},
delivered: {},
};
function* order(start = 'pending') {
let state = start;
const history = [state];
while (Object.keys(TRANSITIONS[state]).length > 0) {
const event = yield state;
const next = TRANSITIONS[state][event];
if (next === undefined) continue; // this state cannot handle that event
state = next;
history.push(state);
}
return history;
}
const o = order();
const a = o.next(); // start it
const b = o.next('pay');
const ignored = o.next('deliver'); // shipping has not happened yet
const c = o.next('ship');
const done = o.next('deliver');
const cancelled = (() => { const x = order(); x.next(); return x.next('cancel'); })();
const independent = (() => {
const p = order(); const q = order();
p.next(); q.next(); p.next('pay');
return q.next('cancel').value;
})();
console.log('pending ->', b.value, '->', c.value);
console.log('an event it cannot handle:', ignored.value, '<- unchanged');
console.log('terminal:', done.done, JSON.stringify(done.value));
console.log('cancelled route:', cancelled.value);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('it starts pending', a.value, 'pending');
test('paying moves it on', b.value, 'paid');
test('an event this state cannot handle is ignored', ignored.value, 'paid');
test('shipping then delivering runs it out', c.value, 'shipped');
test('a terminal state ends the generator', done.done, true);
test('and the return value is the whole history', done.value, ['pending', 'paid', 'shipped', 'delivered']);
test('cancelling from pending is a different terminal state', cancelled, { value: ['pending', 'cancelled'], done: true });
test('each machine holds its own state, so two orders never interfere', independent, ['pending', 'cancelled']);
The state lives in the generator's suspended frame. There is no this.state to be mutated from elsewhere, no reducer to be called with the wrong arguments, and no way to reach the machine except by sending it an event. Two orders in flight are two frames, and the last assertion is the proof that they do not share anything.
Keeping the transitions as a plain table rather than a chain of ifs is what makes "ignore an impossible event" one line instead of a case per state. It also means the terminal check is Object.keys(...).length === 0 rather than a hand-maintained list, so adding refunded needed no code change at all.
The honest limitation: a generator state machine cannot be inspected without advancing it. If you need to ask "what state is it in?" from outside, or to persist and resume it, keep the state in a plain object and use a reducer. The generator wins where the machine is driven by a single consumer, which is exactly the parsing case in exercises 111 to 116.