Skip to content

Instantly share code, notes, and snippets.

@Drag13
Created November 4, 2021 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Drag13/758f3029cedf8c1f202b79b67f814988 to your computer and use it in GitHub Desktop.
Save Drag13/758f3029cedf8c1f202b79b67f814988 to your computer and use it in GitHub Desktop.
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