Facebook Pixel

Event Emitter

JavaScript
medium
25 mins

Design and implement an EventEmitter class that mimics Node.js-style event handling.
It should support the following methods:

  • on(eventName, callback): Register a callback to be called every time the event is triggered.
  • once(eventName, callback): Register a one-time callback (removed after first execution).
  • off(eventName, callback): Remove a specific callback for an event.
  • emit(eventName, ...args): Trigger all callbacks registered for that event with the given arguments.

Input: Method calls to the EventEmitter class.
Output: Appropriate invocations of callbacks.

Example Inputs & Outputs

const emitter = new EventEmitter(); const log = (...args) => console.log(...args); emitter.on('sayHello', log); emitter.emit('sayHello', 'Hi!'); // Output: Hi! emitter.once('sayBye', () => console.log('Bye!')); emitter.emit('sayBye'); // Output: Bye! emitter.emit('sayBye'); // No output emitter.off('sayHello', log); emitter.emit('sayHello', 'Hi again'); // No output

Constraints & Edge Cases

  • off() should not throw errors for unregistered callbacks
  • emit() should handle no listeners gracefully
  • once() handlers should auto-remove after one call
  • Multiple callbacks per event are allowed
  • Callbacks should maintain argument order

Companies:

slack
shopify
flipkart

Solve Similar questions šŸ”„