@naverpay/vanilla-store
Version:
  
50 lines (49 loc) • 1.37 kB
JavaScript
import { applyPersist } from "./applyOptions.mjs";
import { shallowEqual } from "./shallowEqual.mjs";
const createVanillaSelect = (store, selectFn, equalityFn = shallowEqual, options) => {
const callbacks = /* @__PURE__ */ new Set();
let state = selectFn(store.get());
const get = () => {
const persistValue = store.persistStore?.value;
const currentValue = persistValue && !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 = 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
};
};
export {
createVanillaSelect
};