Create a State Machine with a Generator

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

Since generators can take initial values and expose a next method which can run updates on the initial value, it becomes trivial to make a state machine with a generator where you pass your transitions into the next method. This lesson walks through creating a state machine with a generator.

John Lindquist: [0:00] Because we can trap state inside of our generator functions, we can do things like create state machines, so I'll go ahead and create a state machine generator function. This will take an initial state, and to start off with while true yield state. If I create our iterator from our state machine, and start stateMachine off at , I'll console.log out our iterator.next() and that should give me the value of , done of false.

[0:36] In state machines you use transitions to manage our state. I'm going to pass an increment into our second iteration, and define this transition up here, so I'll say let transition, and the transition can just be assigned at the beginning of the next iteration, then we can use the transition above it, so I can say if transition = increment, then state++. I'll hit stave here. Now our state value is 1, and I can increment again, our state value is now 2.

[1:13] We can set up another transition, we can call this one decrement. We'll add a decrement transition decrement, it will say state--. Hit save here, and now we increment, increment, and decrement. We capture the state here inside of the initial call, that first call of next will always get back our initial state, and then from then on, we can manage state by passing values into next, and transitioning that state from one state to another state.