Advertisement
marcusziade

Typescript statemachine

Jan 26th, 2023
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class StateMachine {
  2.     private handlers: {[name: string]: (cargo: any) => string | undefined} = {}
  3.     private startState?: string
  4.     private endStates: string[] = []
  5.     private currentState?: string
  6.     private cargo?: any
  7.     private stateHistory: string[] = []
  8.  
  9.     addState(name: string, handler: (cargo: any) => string | undefined, isEndState = false): void {
  10.         this.handlers[name] = handler
  11.         if (isEndState) {
  12.             this.endStates.push(name)
  13.         }
  14.     }
  15.  
  16.     setStart(name: string): void {
  17.         this.startState = name
  18.     }
  19.  
  20.     setCargo(cargo: any): void {
  21.         this.cargo = cargo
  22.     }
  23.  
  24.     run(): void {
  25.         if (!this.startState || !this.handlers[this.startState]) {
  26.             return
  27.         }
  28.         this.currentState = this.startState
  29.         this.stateHistory.push(this.currentState)
  30.  
  31.         while (!this.endStates.includes(this.currentState)) {
  32.             const nextState = this.handlers[this.currentState](this.cargo)
  33.             if (!nextState) {
  34.                 return
  35.             }
  36.             this.currentState = nextState
  37.             this.stateHistory.push(this.currentState)
  38.         }
  39.     }
  40.  
  41.     getStateHistory(): string[] {
  42.         return this.stateHistory
  43.     }
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement