UNPKG

@lumieslab/stasho

Version:

lightweight state management library

58 lines (57 loc) 2.07 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Store = void 0; /** * Creates a store that can be used to manage state and dispatch actions. * @param initialState the initial state of the store * @param reducers a list of reducers that will be applied to the state * @param memories a list of memory which computes the state * @param effects a list of effects that occur when an action is dispatched * @constructor */ const Store = (initialState, reducers = [], memories = [], effects = []) => { let state = initialState; const memoryState = new Map(); const updateMemories = () => { memories.forEach((memory) => { memoryState.set(memory, memory(state)); }); }; // Dispatch a change const dispatch = (action) => { // Reduce all the states though the action and produce new state = reducers.reduce((state, reducerCallback) => reducerCallback(state, action), state); // Update memory state updateMemories(); // Call effects on all systems effects.forEach((effectCallback) => effectCallback(action)); }; // Returns the memory item using the reference to the memory callback. const getMemory = (reference) => { return memoryState.get(reference); }; // Attaches the reducer callback to the array of reducers const attachReducer = function (reducerCallback) { reducers.push(reducerCallback); }; // Attaches the memory callback to the array of memories const attachMemory = function (memoryCallback) { memories.push(memoryCallback); updateMemories(); }; // Attaches the effect callback to the array of effects const attachEffect = function (effectCallback) { effects.push(effectCallback); }; // Initialise the state of the store updateMemories(); // Controls to interact with store return { dispatch, getMemory, attachReducer, attachMemory, attachEffect }; }; exports.Store = Store;