UNPKG

dreamstate

Version:

Store management library based on react context and observers

28 lines (25 loc) 1.39 kB
import { DreamstateError } from '../core/error/DreamstateError.js'; import { ComputedValue } from '../core/storing/ComputedValue.js'; import { EDreamstateErrorCode } from '../types/error.js'; import { isFunction, isUndefined } from './typechecking.js'; /** * Creates a computed value that will be re-calculated after each context update. * The computed value is recalculated only when its dependencies, as determined by the memo function, * are updated. * * @template T The type of the computed value. * @template C The type of the context the computed value depends on. * @param {Function} selector A generic selector function that returns computed values on update. * @param {Function} memo An optional memo checker function that returns an array of dependencies, * indicating whether the computed value should be updated. * @returns {TComputed<T, C>} A computed value object that will be updated based on context changes. */ function createComputed(selector, memo) { if (isFunction(selector) && (isUndefined(memo) || isFunction(memo))) { // Cast computed to T & TComputed since it works like state object later. return new ComputedValue(selector, memo); } else { throw new DreamstateError(EDreamstateErrorCode.INCORRECT_PARAMETER, "Computed value should be initialized with functional selector and optional memo function."); } } export { createComputed };