Skip to content

2694. Event Emitter 👍

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
type Callback = (...args: any[]) => any;
type Subscription = {
  unsubscribe: () => void;
};

class EventEmitter {
  private eventToCallbacks: Map<string, Callback[]>;

  constructor() {
    this.eventToCallbacks = new Map();
  }

  subscribe(eventName: string, callback: Callback): Subscription {
    if (!this.eventToCallbacks.has(eventName))
      this.eventToCallbacks.set(eventName, []);

    const callbacks = this.eventToCallbacks.get(eventName);
    callbacks?.push(callback);

    return {
      unsubscribe: () => {
        const index = callbacks?.indexOf(callback);
        if (index !== undefined && index !== -1) {
          callbacks?.splice(index, 1);
        }
      },
    };
  }

  emit(eventName: string, args: any[] = []): any[] {
    const callbacks = this.eventToCallbacks.get(eventName);
    if (callbacks === undefined) {
      return [];
    }
    return callbacks.map((callback) => callback(...args));
  }
}