Event Emitter

MediumAirbnbLinkedInGoogleLyftTikTok

Prompt

Your task is to build a basic EventEmitter class in JavaScript. Event emitters are a common pattern used in Node.js and the browser to handle asynchronous actions (like responding to a user click or a network response).

Your class must implement the following three methods:

  • on(eventName, listener): Subscribes a listener function to a specific eventName. Multiple listeners can be subscribed to the same event.
  • off(eventName, listener): Unsubscribes a specific listener function from the eventName. If the listener isn't subscribed, it should do nothing.
  • emit(eventName, ...args): Triggers all listeners subscribed to the eventName in the order they were added, passing any provided args to each listener. If no listeners are subscribed to the event, it should do nothing.

Requirements:

  • You should handle the case where multiple functions are registered to the same event.
  • You should handle emitting events that have no listeners gracefully (without throwing an error).
  • Listeners might need to receive an arbitrary number of arguments when an event is emitted.
  • Event names can be any string, including ones like 'constructor' or 'toString'.