Write a class EventEmitter with on(event, listener), off(event, listener), once(event, listener) and emit(event, ...args).
Listeners run in the order they were added. emit returns true if any listener ran and false otherwise. A once listener runs one time, and it can also be removed early with off(event, listener) using the original function.
Your code
Runs in a Web Worker in your browser. Tests use real timers, so a run takes a second or two.
Solution
class EventEmitter {
constructor() {
this.listeners = new Map();
}
on(event, listener) {
if (!this.listeners.has(event)) this.listeners.set(event, []);
this.listeners.get(event).push(listener);
return this;
}
off(event, listener) {
const list = this.listeners.get(event);
if (!list) return this;
const i = list.findIndex((l) => l === listener || l.original === listener);
if (i !== -1) list.splice(i, 1);
return this;
}
once(event, listener) {
const wrapper = (...args) => {
this.off(event, wrapper);
listener.apply(this, args);
};
wrapper.original = listener;
return this.on(event, wrapper);
}
emit(event, ...args) {
const list = this.listeners.get(event);
if (!list || list.length === 0) return false;
for (const listener of [...list]) listener.apply(this, args);
return true;
}
}
Keep a map from event name to an array of listeners. once wraps the listener in a function that removes itself before calling it, and stores the original on the wrapper so off can still find it.
The subtle part is emit: copy the list before looping ([...list]). Otherwise a once listener removing itself mid-loop shifts the array and the next listener gets skipped. Follow-ups: error handling per listener, wildcard events, and a max-listeners warning.
In a Web Worker in your browser, with real timers and promises. Nothing is sent to a server. If your code loops forever, the run is stopped after 10 seconds.
Yes. Anything your browser supports works: classes, async/await, Map and Set, spread and optional chaining.