Enumerating the possible states of a function is a sound way to write a function, but it is imperative and could benefit from abstraction. We can do this with a state machine.
A state machine formalizes how we enumerate states and transitions. For the sake of clarity and to emphasize the core concepts, I will be overly verbose with my code in this lesson.
In this lesson, we'll replace the state enum with individual state objects. We'll also replace our events toggle()
and break()
with events TOGGLE
and BREAK
. I'll also demonstrate the usefulness of the Machine's initialState
getter and the transition
method. Lastly, I'll show what happens when we pass erroneous states or events into our machine.
I think it could be less-confusing to some to comment-out your ellipses when hiding irrelevant code, otherwise it looks like you're trying to use the rest operator.