@ai2070/l0
Version:
L0: The Missing Reliability Substrate for AI
87 lines (86 loc) • 1.81 kB
JavaScript
function combineEvents(...handlers) {
const validHandlers = handlers.filter(
(h) => typeof h === "function"
);
if (validHandlers.length === 0) {
return () => {
};
}
if (validHandlers.length === 1) {
return validHandlers[0];
}
return (event) => {
for (const handler of validHandlers) {
try {
handler(event);
} catch (error) {
console.error(
`Event handler error for ${event.type}:`,
error instanceof Error ? error.message : error
);
}
}
};
}
function filterEvents(types, handler) {
const typeSet = new Set(types);
return (event) => {
if (typeSet.has(event.type)) {
handler(event);
}
};
}
function excludeEvents(types, handler) {
const typeSet = new Set(types);
return (event) => {
if (!typeSet.has(event.type)) {
handler(event);
}
};
}
function debounceEvents(ms, handler) {
let timeout = null;
let latestEvent = null;
return (event) => {
latestEvent = event;
if (timeout === null) {
timeout = setTimeout(() => {
if (latestEvent) {
handler(latestEvent);
}
timeout = null;
latestEvent = null;
}, ms);
}
};
}
function batchEvents(size, maxWaitMs, handler) {
let batch = [];
let timeout = null;
const flush = () => {
if (batch.length > 0) {
handler([...batch]);
batch = [];
}
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
};
return (event) => {
batch.push(event);
if (batch.length >= size) {
flush();
} else if (!timeout) {
timeout = setTimeout(flush, maxWaitMs);
}
};
}
export {
batchEvents,
combineEvents,
debounceEvents,
excludeEvents,
filterEvents
};
//# sourceMappingURL=event-handlers.js.map