JavaScriptFundamental (ES6), part 1
State machine with a lookup table in JavaScript
116 a state machine as a frozen lookup table
fairModel an order's life — placed, packed, dispatched, delivered, cancelled — as one frozen object of states to events to next states. Write next(state, event) so an event the current state does not allow leaves the state alone, feed a list of events through reduce, and collect both the trail of states and the events that were ignored. Then show what Object.freeze did not freeze.
Stuck? Three hints, smallest first
- 1. The table is
{ placed: { pack: 'packed' } }: two lookups, a state then an event. - 2.
machine[state]?.[event] ?? statecovers an unknown event and an unknown state in one line. - 3. The reducer carries an object, not a string:
{ state, trail, ignored }, rebuilt with spread each step.
const machine = Object.freeze({
placed: { pack: 'packed', cancel: 'cancelled' },
packed: { dispatch: 'dispatched', cancel: 'cancelled' },
dispatched: { deliver: 'delivered' },
delivered: {},
cancelled: {},
});
const next = (state, event) => machine[state]?.[event] ?? state;
const eventsFrom = (state) => Object.keys(machine[state] ?? {});
const isTerminal = (state) => eventsFrom(state).length === 0;
const feed = (start, events) => events.reduce((acc, event) => {
const to = next(acc.state, event);
return to === acc.state
? { ...acc, ignored: [...acc.ignored, event] }
: { ...acc, state: to, trail: [...acc.trail, to] };
}, { state: start, trail: [start], ignored: [] });
const happy = feed('placed', ['pack', 'dispatch', 'deliver']);
const stubborn = feed('placed', ['deliver', 'pack', 'cancel', 'pack']);
const fromNowhere = next('warehouse-9', 'pack');
let topLevelWrite = 'no error';
try { machine.placed = {}; } catch (e) { topLevelWrite = e.constructor.name; }
const nestedIsFrozen = Object.isFrozen(machine.placed);
console.log('happy :', happy.state, happy.trail);
console.log('stubborn :', stubborn.state, '| ignored:', stubborn.ignored);
console.log('terminal :', ['delivered', 'cancelled', 'placed'].map(isTerminal));
console.log('freeze :', topLevelWrite, '| nested frozen:', nestedIsFrozen);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the happy path ends delivered', happy.state, 'delivered');
test('and its trail is every state it passed through', happy.trail, ['placed', 'packed', 'dispatched', 'delivered']);
test('nothing was refused along the way', happy.ignored, []);
test('an event the state does not allow is dropped, not an error', [stubborn.state, stubborn.ignored], ['cancelled', ['deliver', 'pack']]);
test('so the trail only records real moves', stubborn.trail, ['placed', 'packed', 'cancelled']);
test('a state with no events left is terminal', ['delivered', 'cancelled', 'placed'].map(isTerminal), [true, true, false]);
test('an unknown state returns itself, thanks to optional chaining', fromNowhere, 'warehouse-9');
test('the table lists what each state can do', eventsFrom('packed'), ['dispatch', 'cancel']);
test('freeze stops a write to the table, but only the top level', [topLevelWrite, nestedIsFrozen], ['TypeError', false]);
A state machine written as data is worth more than the same thing written as ifs, because the table is inspectable: eventsFrom and isTerminal are one line each, and a UI can grey out the buttons for events the current state does not offer. Adding a state is a new key, not a new branch in five places.
machine[state]?.[event] ?? state is doing three jobs. The ?. handles a state that is not in the table, the missing key handles an event that state does not allow, and ?? — not || — supplies the fallback, which matters the day a state is named with a falsy-looking value.
The last assertion is the trap. Object.freeze is one level deep: the table cannot be reassigned, but machine.placed is an ordinary mutable object, so machine.placed.pack = 'lost' would succeed and silently rewire the machine. Exercise 126 fixes that with a recursive freeze.