UNPKG

@signaldb/core

Version:

SignalDB is a client-side database that provides a simple MongoDB-like interface to the data with first-class typescript support to achieve an optimistic UI. Data persistence can be achieved by using storage providers that store the data through a JSON in

34 lines (33 loc) 1.24 kB
//#region src/utils/createSignal.ts /** * Creates a reactive signal for managing state and triggering dependencies. * The signal holds a value and provides methods to get and set the value, * with optional equality checks and dependency tracking. * @template T - The type of the value held by the signal. * @param reactivityAdapter - An optional reactivity adapter for managing dependencies. * @param initialValue - The initial value of the signal. * @param isEqual - A custom equality function to determine if the new value is different * from the current value (default is `Object.is`). * @returns A signal object with `get` and `set` methods to manage the value. */ function createSignal(reactivityAdapter, initialValue, isEqual = Object.is) { let value = initialValue; const dependency = reactivityAdapter?.create(); const isInReactiveScope = () => { if (!reactivityAdapter?.isInScope) return true; return reactivityAdapter.isInScope(); }; return { get() { if (dependency && isInReactiveScope()) dependency.depend(); return value; }, set(newValue) { if (isEqual(value, newValue)) return; value = newValue; if (dependency) dependency.notify(); } }; } //#endregion export { createSignal as default };