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:
subscribe(eventName, callback): Allows a user to provide a callback for a specific event. It should return a way to "unsubscribe."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.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.
The problem uses a Hash Map of Arrays (or Sets).
eventName and the value is a list of callback functions.unsubscribe method that removes that specific callback from the list.emitter.subscribe("greet", (name) => "Hello " + name)emitter.subscribe("greet", (name) => "Hi " + name)emitter.emit("greet", ["Alice"])
["Hello Alice", "Hi Alice"].emitter.emit("greet", ["Alice"]) returns ["Hi Alice"].Set or giving each subscription a unique ID can be more efficient.this binding if the class is implemented in certain ways (though modern arrow functions simplify this).emit is called for an event that has no subscribers (it should return an empty array, not crash).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.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Square Submatrices with All Ones | Medium | Solve | |
| Count Complete Subarrays in an Array | Medium | Solve | |
| Random Pick Index | Medium | Solve | |
| Redundant Connection | Medium | Solve | |
| Binary Tree Longest Consecutive Sequence | Medium | Solve |