⚡Flashcard Drill➔
NeetCode #970LC-2694MediumJavaScript
← Back to All Problems

#970 · #2694 · Event Emitter(事件发射器)

📌 Problem Statement & Constraints

Implement an EventEmitter class: subscribe(eventName, callback) registers a callback and returns an object with an unsubscribe() method; emit(eventName, args) synchronously invokes all callbacks for that event and returns an array of their results. Constraints: at most 10^4 calls.

💡 Core Algorithmic Approaches

  1. Store listeners in a Map from event name to an array of callbacks.
  2. subscribe creates the array on demand, pushes the callback, and returns an unsubscribe that removes exactly that callback with indexOf plus splice.
  3. emit invokes every callback in registration order, spreads args, and collects the results into an array.
  4. When an event has no subscribers, emit returns an empty array.

💻 Benchmark Python3 Implementation

class EventEmitter {
    constructor() {
        this.events = new Map();
    }

    subscribe(event, cb) {
        if (!this.events.has(event)) {
            this.events.set(event, []);
        }
        const list = this.events.get(event);
        list.push(cb);
        return {
            unsubscribe: () => {
                const i = list.indexOf(cb);
                if (i !== -1) list.splice(i, 1);   // remove only this callback
            }
        };
    }

    emit(event, args = []) {
        const list = this.events.get(event) || [];
        return list.map(cb => cb(...args));
    }
}

⚡ Complexity Deep Dive

⏱️ Time Complexity
subscribe is O(1); emit and unsubscribe are O(k) over k listeners for the event.
💾 Space Complexity
O(m): m is the total number of callbacks.

⚠️ Interview Pitfalls & Follow-ups

  • Rebuilding the array with filter in unsubscribe: that removes every equal callback reference; splice removes only the intended one.
  • Using forEach in emit: it returns nothing, but an array of results is required.
  • Passing args without spreading: callbacks would receive a single array argument instead of separate parameters.
  • Throwing when the event has no subscribers: emit should return an empty array.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related JavaScript Problems