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.

egghead
egghead
~ 5 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today