Implement Event Emitter

MediumDesign Patterns20 min4 tests

Implement an EventEmitter class with subscribe/unsubscribe/emit functionality.

Requirements

  • on(event, callback) - Subscribe to an event
  • off(event, callback) - Unsubscribe from an event
  • emit(event, ...args) - Trigger all callbacks for an event
  • once(event, callback) - Subscribe for only one invocation

Example

const emitter = new EventEmitter();
emitter.on('greet', (name) => console.log(`Hello, ${name}!`));
emitter.emit('greet', 'World'); // "Hello, World!"
Hints (5)
  1. Use a Map to store event names and their callback arrays.
  2. For on, push the callback to the array for that event.
  3. For off, find and remove the specific callback from the array.
  4. For emit, iterate through all callbacks and invoke them with the args.
  5. For once, create a wrapper that calls off before invoking the original callback.

Topics

  • Design Patterns

Asked at

Meta · Google · Microsoft · Shopify

Join Us
blur