Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class StateMachine {
- private handlers: {[name: string]: (cargo: any) => string | undefined} = {}
- private startState?: string
- private endStates: string[] = []
- private currentState?: string
- private cargo?: any
- private stateHistory: string[] = []
- addState(name: string, handler: (cargo: any) => string | undefined, isEndState = false): void {
- this.handlers[name] = handler
- if (isEndState) {
- this.endStates.push(name)
- }
- }
- setStart(name: string): void {
- this.startState = name
- }
- setCargo(cargo: any): void {
- this.cargo = cargo
- }
- run(): void {
- if (!this.startState || !this.handlers[this.startState]) {
- return
- }
- this.currentState = this.startState
- this.stateHistory.push(this.currentState)
- while (!this.endStates.includes(this.currentState)) {
- const nextState = this.handlers[this.currentState](this.cargo)
- if (!nextState) {
- return
- }
- this.currentState = nextState
- this.stateHistory.push(this.currentState)
- }
- }
- getStateHistory(): string[] {
- return this.stateHistory
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement