Generators as State Machines

Most implementations of generators end up being state machines. This means instead of implementing explicit state machines one can use generators to keep the state implicit and let the compiler do the hard work of converting the generator to an explicit state machine. The downside of generator based approach is that it becomes much harder to serialize the state for persistence. The upside is there is less juggling of state overall because one can use the control flow facilities of the language in which the generator is embedded to keep track of the state.

I recently built a small library for expressing state machines in TypeScript and I used a 3 story elevator as an example

If you follow the logic then you’ll notice something about the elevator. All it does is cycle through the states in a deterministic order

There is another way to express this cyclic behavior and that’s with generators

If you target ES5 and compile that with TypeScript then you will literally get a state machine

I haven’t yet decided in which instances you’d want to use generators vs explicit state machines but the fact that there is an equivalence means there are instances in which the generator approach is the correct one to use. Anything that requires complicated state tracking with more than a few variables should probably be expressed as a generator.