zustand-duck
Version:
Simple reducer writing and cross-process state sharing.
59 lines • 1.71 kB
JavaScript
export class SharedDuckChannels {
defaultChannel = '';
listeners = [];
get default() {
return this.defaultChannel;
}
set default(channel) {
this.defaultChannel = channel;
}
notify(channel, event) {
this.listeners.forEach(fn => fn(channel, event));
}
subscribe(listener) {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter(l => l !== listener);
};
}
}
export const shareWithChannels = (channels, creator) => {
const storeMap = new Map();
const store = {};
const getStoreWithChannel = (channel) => {
if (!storeMap.has(channel)) {
storeMap.set(channel, creator(channel));
}
return storeMap.get(channel);
};
channels.subscribe((channel, event) => {
switch (event) {
case 'add': {
getStoreWithChannel(channel);
break;
}
case 'remove': {
storeMap.delete(channel);
break;
}
}
});
// create default store listen port message
getStoreWithChannel(channels.default);
return new Proxy(store, {
get: (target, key) => {
if (key === 'channel') {
return getStoreWithChannel;
}
if (store[key] !== void 0 || typeof key === 'symbol') {
return store[key];
}
return getStoreWithChannel(channels.default ?? '')?.[key];
},
set: (target, key, value) => {
store[key] = value;
return true;
},
});
};
//# sourceMappingURL=shared-duck-channel.js.map