Created
November 4, 2021 06:47
-
-
Save Drag13/758f3029cedf8c1f202b79b67f814988 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IStateMachine<TState,TEvent, TPayload = {}> { | |
getState():TState; | |
dispatch(event: TEvent, payload?: TPayload): IStateMachine<TState,TEvent, TPayload>; | |
} | |
type MyEvent = 'start' | 'move' | 'stop'; | |
type MyState = {speed: number, isHealthy: boolean}; | |
class MyStateMachine implements IStateMachine<MyState, MyEvent> { | |
constructor(private _state: MyState, private readonly _reaction: Record<MyEvent,(state:MyState)=> MyState>){} | |
getState(): MyState { | |
return this._state; | |
} | |
dispatch(event: MyEvent) { | |
const reaction = this._reaction[event]; | |
this._state = reaction(this._state); | |
console.log(this._state); | |
return this; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment