class EventBus {
#listeners = new Map();
on(event, cb) {
if (!this.#listeners.has(event)) this.#listeners.set(event, []);
this.#listeners.get(event).push(cb);
return this;
}
emit(event, ...args) {
const cbs = this.#listeners.get(event) || [];
return cbs.map(cb => cb(...args));
}
}
const bus = new EventBus();
bus.on('data', x => x * 2).on('data', x => x + 1);
const results = bus.emit('data', 5);
console.log(results, bus.emit('missing', 1)); Post #3560
325
CHALLENGE
- ❤ 1