export interface StateMachineTransitionResult { state: State; effects: Effect[]; } export type StateMachineTransition = ( state: State, context: Context, event: Event ) => StateMachineTransitionResult; export interface StateMachineContainer { readonly state: State; dispatch(event: Event, context: Context): StateMachineTransitionResult; setState(nextState: State): void; reset(): void; } interface CreateStateMachineOptions { initialState: State; transition: StateMachineTransition; } /** * * @param options */ export function createStateMachine( options: CreateStateMachineOptions ): StateMachineContainer { let currentState = options.initialState; return { get state(): State { return currentState; }, dispatch(event: Event, context: Context): StateMachineTransitionResult { const transition = options.transition(currentState, context, event); currentState = transition.state; return transition; }, setState(nextState: State): void { currentState = nextState; }, reset(): void { currentState = options.initialState; }, }; }