UNPKG

@qiwi/cyclone

Version:

"State machine" for basic purposes

112 lines (111 loc) 3.15 kB
declare type IState = string; declare type IAny = any; declare type IHandler = (data: IAny, ...payload: Array<IAny>) => IAny; declare type ITransitions = { [key: string]: IHandler | null | boolean; }; declare type IMachineOpts = { transitions: ITransitions; initialState?: IState; initialData?: IAny; immutable?: boolean; historySize?: number; }; export declare const DELIMITER = ">"; export declare const DEFAULT_HANDLER: IHandler; export declare const DEFAULT_HISTORY_SIZE = 10; export declare const DEFAULT_OPTS: IMachineOpts; declare type IKey = string | null; declare type IDigest = { state?: IState; data?: IAny; }; declare type IHistoryItem = { state: IState; data: IAny; id: string; date: Date; }; declare type IHistory = IHistoryItem[]; interface IMachine { next(state: IState, ...payload: Array<IAny>): IMachine; prev(state?: IState): IMachine; current(): IDigest; lock(key?: IKey): IMachine; unlock(key: IKey): IMachine; transitions: ITransitions; history: IHistory; opts: IMachineOpts; key: IKey; id: string; } declare type IPredicate = (item: IHistoryItem) => boolean; export declare class Machine implements IMachine { /** * Machine options. * @property */ opts: IMachineOpts; /** * State history. * @property */ history: IHistory; /** * Lock key. * @property */ key: IKey; /** * Unique machine id * @property */ id: string; /** * Transition handler map * @property */ transitions: ITransitions; constructor(opts: IMachineOpts); /** * Provides next state transition. * @param state Next state name. * @param payload Any data for handler. */ next(state: IState, ...payload: Array<IAny>): IMachine; /** * Returns the machine's digest: state name and stored data. */ current(): IHistoryItem; /** * Returns the last state, that satisfies the condition */ last(condition?: string | IPredicate): IHistoryItem | void; /** * Reverts current state to the previous. * @param state */ prev(state?: string | IPredicate): IMachine; /** * Locks the machine. Any transitions are prohibited before unlocking. * @param key */ lock(key?: IKey): IMachine; /** * Unlocks the machine. * @param key */ unlock(key: IKey): IMachine; static getHistoryLimit(historySize?: number): number; static getHandler(next: IState, history: IHistory, transitions: ITransitions): IHandler; static getTransition(targetTransition: string, transitions: ITransitions): string | void; static getTargetTransition(next: IState, history: IHistory): string; /** * Returns the last passes argument as a result * @param {any} state * @param {any} [payload] * @return {any} */ DEFAULT_HANDLER: IHandler; } export { IMachine, IHistory, ITransitions, IHistoryItem, IHandler, IMachineOpts };