UNPKG

jotai

Version:

👻 Primitive and flexible state management for React

29 lines (28 loc) • 1.12 kB
import { atom } from '../../vanilla.js'; const getCached = (c, m, k) => (m.has(k) ? m : m.set(k, c())).get(k); const cache1 = new WeakMap(); const memo3 = (create, dep1, dep2, dep3) => { const cache2 = getCached(() => new WeakMap(), cache1, dep1); const cache3 = getCached(() => new WeakMap(), cache2, dep2); return getCached(create, cache3, dep3); }; export function selectAtom(anAtom, selector, equalityFn = Object.is) { return memo3(() => { const EMPTY = Symbol(); const selectValue = ([value, prevSlice]) => { if (prevSlice === EMPTY) { return selector(value); } const slice = selector(value, prevSlice); return equalityFn(prevSlice, slice) ? prevSlice : slice; }; const derivedAtom = atom((get) => { const prev = get(derivedAtom); const value = get(anAtom); return selectValue([value, prev]); }); // HACK to read derived atom before initialization derivedAtom.init = EMPTY; return derivedAtom; }, anAtom, selector, equalityFn); }