zephyr-events
Version:
Ultra-fast ES2023 event emitter with 889B bundle size and race-condition safety
56 lines (55 loc) • 1.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = zephyrEvents;
function zephyrEvents(all) {
all ??= new Map();
const handlerSets = new Map();
const getHandlerSet = (type) => {
let handlers = handlerSets.get(type);
if (!handlers) {
handlers = new Set();
handlerSets.set(type, handlers);
all.set(type, []);
}
return handlers;
};
const syncMap = (type) => {
const handlers = handlerSets.get(type);
if (handlers) {
all.set(type, [...handlers]);
}
};
return {
all,
on(type, handler) {
const handlers = getHandlerSet(type);
handlers.add(handler);
syncMap(type);
return () => {
handlers.delete(handler);
syncMap(type);
};
},
off(type, handler) {
const handlers = handlerSets.get(type);
if (!handlers)
return;
handler ? handlers.delete(handler) : handlers.clear();
syncMap(type);
},
emit(type, evt) {
const handlers = handlerSets.get(type);
if (handlers?.size) {
for (const handler of [...handlers]) {
handler(evt);
}
}
const wildcards = handlerSets.get('*');
if (wildcards?.size) {
for (const handler of [...wildcards]) {
handler(type, evt);
}
}
}
};
}