@snipsonian/observable-state
Version:
Observable-state snippets (redux-like)
53 lines (52 loc) • 2.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const isArray_1 = require("@snipsonian/core/cjs/is/isArray");
const extendNotificationsToTrigger_1 = require("./extendNotificationsToTrigger");
function createStateObserverManager() {
let observerCounter = 0;
const observerMap = {};
return {
registerObserver: ({ observerName, notificationsToObserve, onNotify, }) => {
observerCounter += 1;
const observer = {
id: observerCounter,
observerName,
notify: onNotify,
};
observerMap[observer.id] = Object.assign(Object.assign({}, observer), { notificationsToObserve });
return observer;
},
unRegisterObserver: (observer) => {
delete observerMap[observer.id];
},
notifyObserversOfStateChanges: ({ notificationsToTrigger, triggerParentNotifications, }) => {
if ((0, isArray_1.default)(notificationsToTrigger) && notificationsToTrigger.length > 0) {
const uniqueObserversToNotify = (0, extendNotificationsToTrigger_1.default)({
notificationsToTrigger,
triggerParentNotifications,
})
.reduce((accumulator, notificationToTrigger) => {
const matchingObservers = Object.values(observerMap)
.filter((registeredObserver) => registeredObserver.notificationsToObserve.includes(notificationToTrigger));
matchingObservers.forEach((observer) => {
const alreadyFoundObserver = accumulator
.find((observerToNotify) => observerToNotify.id === observer.id);
if (alreadyFoundObserver) {
alreadyFoundObserver.notifications.push(notificationToTrigger);
}
else {
accumulator.push(Object.assign(Object.assign({}, observer), { notifications: [notificationToTrigger] }));
}
});
return accumulator;
}, []);
if (uniqueObserversToNotify && uniqueObserversToNotify.length > 0) {
uniqueObserversToNotify.forEach((observerToNotify) => {
observerToNotify.notify({ notifications: observerToNotify.notifications });
});
}
}
},
};
}
exports.default = createStateObserverManager;