News for hackers. Stuff that matters.
Re:Facts about State Machines by presentation on Friday September 30, 2022 @08:46PM (#33042612)
JavaScript has libraries for this (xstate) but I usually just do it something like this in typescript:

    enum State { A, B, C };
    enum Action { A, B };
    
    type StateData = 
      | { state: State.A, data: whatever }
      | { state: State.B, data: whatever }
      | { state: State.C, data: whatever };
    
    type ActionData = 
      | { type: Action.A, data: whatever }
      | { type: Action.B, data: whatever };

    function transition(prev: StateData, action: ActionData): StateData {
      switch(action.type) {
        case Action.A:
          return { type: State.B, data: whatever };
        case Action.B:
          return { type: State.C, data: whatever };
      }
    }
Then you can for example if you were using this in react do something like

    function MyComponent() {
        const [state, setState] = useState<StateData>({ state: State.A, data: whatever });

        return <button onClick={() => setState(transition(state, { action: Action.A, data: whatever }))}>Go!</button>;
    }

There are no comments on this comment yet.