UNPKG

react-native-onyx

Version:

State management for React Native

38 lines (37 loc) 1.31 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * An immutable, type-safe finite state machine. * Pass the transition graph with `as const` so `transition` only accepts legal target states. * * @example * const transitions = { * idle: ['loading'], * loading: ['success', 'error'], * success: [], * error: ['idle'], * } as const; * * const idleMachine = new StateMachine('idle', transitions); * const loadingMachine = idleMachine.transition('loading'); * loadingMachine.transition('success'); */ class StateMachine { constructor(currentState, transitions) { this.state = currentState; this.transitions = transitions; Object.freeze(this); } /** * Transition to a new state, returning a new state machine instance. * Only transitions declared in the graph for the current state are accepted. */ transition(target) { const validTargets = this.transitions[this.state]; if (!(validTargets === null || validTargets === void 0 ? void 0 : validTargets.includes(target))) { throw new Error(`Illegal transition from "${String(this.state)}" to "${String(target)}"`); } return new StateMachine(target, this.transitions); } } exports.default = StateMachine;