const ATOM_SYMBOL = Symbol('atom'); export const isAtom = (value) => { return value?.[ATOM_SYMBOL] === true; }; export const atom = (initialValue) => { let value = null; const subscribers = new Set(); if (typeof initialValue !== "undefined") value = initialValue; return { [ATOM_SYMBOL]: true, get value() { return value; }, set(data) { const nextValue = typeof data === "function" ? data(value) : data; if (Object.is(value, nextValue)) return; value = nextValue; subscribers.forEach(({ until }) => until && until()); subscribers.forEach(({ cb }) => cb(value)); }, mutate(cb) { cb(value); subscribers.forEach(({ until }) => until && until()); subscribers.forEach(({ cb }) => cb(value)); }, subscribe(cb, options = { lazy: false }) { const subscriber = { cb }; subscribers.add(subscriber); if (!options.lazy) cb(value); const subscription = { unsubscribe: () => subscribers.delete(subscriber), until: (condition) => { subscriber.until = () => condition(value) ? subscription.unsubscribe() : null; }, }; return subscription; }, }; }; export const derived = (cb, dependencies) => { const _dependencies = new Set(dependencies); const internalAtom = atom(cb()); _dependencies.forEach((dep) => { dep.subscribe(() => internalAtom.set(cb())); }); return { [ATOM_SYMBOL]: true, get value() { return internalAtom.value; }, subscribe: internalAtom.subscribe, }; };