call(back)
FrontendmediumSign in to star problems

Implement an Event Emitter

Write a class EventEmitter with:

  • on(event, listener) — subscribe; returns the emitter so calls chain. The same listener may be added more than once and then fires once per subscription.
  • off(event, listener) — remove one subscription of that listener (the most recently added), if any; returns the emitter.
  • emit(event, ...args) — call every listener of the event with the arguments, in subscription order; returns true if there was at least one listener, else false.
const emitter = new EventEmitter();
emitter.on("sum", (a, b) => console.log(a + b)).on("sum", (a, b) => console.log(a * b));
emitter.emit("sum", 2, 3);   // logs 5 then 6, returns true
emitter.emit("nothing");     // false

Hints

Hint 1

A Map from event name to an array of listeners keeps subscription order and allows duplicates.

Hint 2

Iterate over a copy of the array in emit: a listener that calls off on itself must not shift the others out of the loop.

Asked at