Magicsheet logo

Event Emitter

Medium
58.8%
Updated 6/1/2025

Asked by 5 Companies

Topics

Event Emitter

What is this problem about?

The Event Emitter coding problem is a system design and object-oriented programming task, usually in JavaScript or TypeScript. You need to implement an EventEmitter class that allows users to subscribe to events and emit them. The class should support two main methods:

  1. subscribe(eventName, callback): Allows a user to provide a callback for a specific event. It should return a way to "unsubscribe."
  2. emit(eventName, args): Executes all registered callbacks for the given event, passing the provided arguments. It should return an array of results from all callbacks.

Why is this asked in interviews?

Companies like Meta, Amazon, and TikTok ask this to test your understanding of the Observer Pattern. It evaluates how you handle data structures (like maps of arrays) and whether you can manage function references. It’s a core concept in frontend frameworks (like the DOM event system or Node.js events) and tests your ability to write clean, reusable library code.

Algorithmic pattern used

The problem uses a Hash Map of Arrays (or Sets).

  1. Storage: Use a Map where the key is the eventName and the value is a list of callback functions.
  2. Subscribe: Add the callback to the list for that event. To handle unsubscription, return an object with an unsubscribe method that removes that specific callback from the list.
  3. Emit: Look up the event name in the map. If it exists, iterate through the list of callbacks, call each one with the arguments, and collect the results.

Example explanation

  1. emitter.subscribe("greet", (name) => "Hello " + name)
  2. emitter.subscribe("greet", (name) => "Hi " + name)
  3. emitter.emit("greet", ["Alice"])
    • First callback returns "Hello Alice".
    • Second callback returns "Hi Alice".
    • Final return: ["Hello Alice", "Hi Alice"].
  4. Unsubscribe the first callback.
  5. emitter.emit("greet", ["Alice"]) returns ["Hi Alice"].

Common mistakes candidates make

  • Unsubscribe efficiency: Removing a callback from an array can be O(N). If there are many subscriptions, using a Set or giving each subscription a unique ID can be more efficient.
  • Context Handling: Not considering this binding if the class is implemented in certain ways (though modern arrow functions simplify this).
  • Empty Events: Not handling the case where emit is called for an event that has no subscribers (it should return an empty array, not crash).

Interview preparation tip

Be ready to discuss why you chose a Map over an Object and why you returned an object for unsubscription rather than having a separate unsubscribe method on the main class. This shows you think about the user experience of your API.

Similar Questions