1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Replace Enumerated States with a State Machine

    xstateXState
    >=4.6.7

    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.