UNPKG

@naverpay/vanilla-store

Version:

![NPM Version](https://img.shields.io/npm/v/%40naverpay%2Fvanilla-store) ![NPM bundle size](https://img.shields.io/bundlephobia/min/%40naverpay%2Fvanilla-store) ![NPM Downloads](https://img.shields.io/npm/dw/%40naverpay%2Fvanilla-store)

50 lines (49 loc) 1.51 kB
"use strict"; Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); const applyOptions = require("./applyOptions.js"); const shallowEqual = require("./shallowEqual.js"); const createVanillaSelect = (store, selectFn, equalityFn = shallowEqual.shallowEqual, options) => { const callbacks = /* @__PURE__ */ new Set(); let state = selectFn(store.get()); const get = () => { const persistValue = store.persistStore?.value; const currentValue = persistValue && !shallowEqual.shallowEqual(persistValue, store.get()) ? persistValue : store.get(); const next = selectFn(currentValue); if (!equalityFn(next, state)) { state = next; return next; } return state; }; let persistStore = null; const addCallbacks = () => callbacks.add(() => { if (persistStore) { persistStore.value = get(); } }); persistStore = applyOptions.applyPersist(options, addCallbacks, selectFn(store.get())); const subscribe = (callback) => { callbacks.add(callback); const unsubscribeOriginalStore = store.subscribe(() => { const next = selectFn(store.get()); if (!equalityFn(next, state)) { state = next; callback(); } }); return () => { callbacks.delete(callback); unsubscribeOriginalStore(); }; }; const set = () => { callbacks.forEach((callback) => callback()); }; return { get, set, subscribe, persistStore }; }; exports.createVanillaSelect = createVanillaSelect;