Skip to content
Onsite

Event Emitter

MediumP1Coding

Implement a class EventEmitter with four methods:

  • on(event, listener): register a listener for event. Returns the emitter so calls can be chained.
  • off(event, listener): remove one registration of that listener. Removing a listener that is not registered does nothing. Returns the emitter.
  • once(event, listener): like on, but the listener runs at most once. off(event, listener) with the original function must also cancel a once registration that has not fired. Returns the emitter.
  • emit(event, ...args): call every listener of event in registration order, passing args. Returns true if there was at least one listener, otherwise false.

Edge rules: a listener that removes itself (or others) while emit is running must not cause listeners to be skipped in that same emit. The same function registered twice runs twice.

Example 1

Input
const e = new EventEmitter(); e.on('hi', n => log(n)); e.emit('hi', 1);
Output
log(1) runs; emit returns true

Constraints

  • Event names are strings
  • Listeners are functions
  • At most 10^4 listeners per event

Hints

Run checks the 3 visible tests, Submit all 11.