@naverpay/vanilla-store
Version:
  
50 lines (49 loc) • 1.51 kB
JavaScript
;
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;