FrontendInterviews.dev

Loading problem…

7. Event Emitter II

Medium•
Acceptance: 73.91%
•
🔓3/3 Pro unlocks today

This problem builds on event-emitter-i. Complete that first, then load your solution to continue.

Implement an EventEmitter class with on, off, once, and emit methods.

This version builds on the basic EventEmitter by adding:

1) once(event, handler) — handler runs at most once.

2) emit(event, ...args) returns an array of handler return values.

Requirements

Methods

  • on(event, handler)
  • Register a handler for an event.
  • Return this (chainable).
  • once(event, handler)
  • Register a handler that runs at most once.
  • Return this.
  • off(event, handler)
  • Remove the matching handler for the event (if present).
  • Return this.
  • emit(event, ...args)
  • Call all handlers for the event in registration order.
  • Pass ...args to each handler.
  • Remove any once handlers after they run.
  • Return an array of handler return values (in call order).

Example

const ee = new EventEmitter();

const calls = [];
ee.on('a', (x) => { calls.push('on'); return x + 1; });
ee.once('a', () => { calls.push('once'); return 99; });

const r1 = ee.emit('a', 1); // ['on' return, 'once' return] => [2, 99]
const r2 = ee.emit('a', 1); // once removed => [2]

// calls => ['on', 'once', 'on']

Constraints

  • Handlers run in registration order.
  • `once` handlers execute at most once per registration and are removed after the first successful call.
  • `emit` returns an array of handler return values in the same order handlers were executed.
  • `off(event, handler)` removes only the matching handler reference for that event.