UNPKG

syncbasestore

Version:

Lightweight reactive store with built-in filtering and async state handling

36 lines (35 loc) 1.25 kB
const originalStateMap = new WeakMap(); function ensureOriginalState(store) { if (!originalStateMap.has(store)) { const cloned = structuredClone ? structuredClone(store.getState()) : JSON.parse(JSON.stringify(store.getState())); originalStateMap.set(store, cloned); } } export function clearBase(store, key) { ensureOriginalState(store); const initial = originalStateMap.get(store)[key]; store.build(prev => ({ ...prev, [key]: initial })); } export function clearBaseKeep(store, key, keepFields) { ensureOriginalState(store); const current = store.getState()[key]; const initial = originalStateMap.get(store)[key]; const keepSet = new Set(keepFields); const next = {}; for (const k in current) { next[k] = keepSet.has(k) ? current[k] : initial[k]; } store.build(prev => ({ ...prev, [key]: next })); } export function clearBaseOnly(store, key, ...fieldsToClear) { ensureOriginalState(store); const current = store.getState()[key]; const initial = originalStateMap.get(store)[key]; const next = { ...current }; for (const f of fieldsToClear) { next[f] = initial[f]; } store.build(prev => ({ ...prev, [key]: next })); }