UNPKG

state-management-utilities

Version:
69 lines (68 loc) 2.06 kB
import cloneDeep from "lodash.clonedeep"; import { center } from "./center"; import { StateManager } from "./state-manager"; export class StateManagerStore { _uid; _config; _initialValues; _KEYS; _initializeEntity(initialValue, config) { return new StateManager(initialValue, config); } entities; constructor(initialValues, _uid = `SMS-#${++counter}`, _config = {}) { this._uid = _uid; this._config = _config; this._initialValues = initialValues; this._KEYS = Object.keys(initialValues); this.entities = Object.freeze(this._KEYS.reduce((acc, key) => { acc[key] = this._initializeEntity(initialValues[key], { ...this._config[key], uid: `${this._uid}/${key}`, }); return acc; }, {})); } set value(value) { for (const key in this.entities) { if (this.entities[key]) this.entities[key].value = value?.[key]; } } get value() { const valueClone = {}; for (const key in this.entities) { if (this.entities[key]) valueClone[key] = this.entities[key].value; } return valueClone; } reset() { for (const key in this.entities) { if (this.entities[key]) this.entities[key].reset(); } } get initialValues() { return center.disableCloning ? this._initialValues : cloneDeep(this._initialValues); } async fulfill() { await Promise.all(this._KEYS.map((key) => this.entities[key].fulfill())); return this; } hydrate(value) { return { update: (record) => { for (const key in this.entities) { if (value[key] === undefined) continue; record[this.entities[key].uid] = { value: value[key] }; } }, value, }; } } let counter = 0;