forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event-emitter.ts
40 lines (36 loc) · 1 KB
/
event-emitter.ts
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
38
39
40
// Time: subscribe: O(1)
// unsubscribe: O(1)
// emit: O(n)
// Space: O(n)
type Callback = (...args: any[]) => any;
type Subscription = {
unsubscribe: () => void
}
// ordered set
class EventEmitter {
#lookup: Map<string, Set<Callback>>;
constructor() {
this.#lookup = new Map<string, Set<Callback>>();
}
subscribe(eventName: string, callback: Callback): Subscription {
if (!this.#lookup.has(eventName)) {
this.#lookup.set(eventName, new Set());
}
this.#lookup.get(eventName).add(callback);
return {
unsubscribe: () => {
this.#lookup.get(eventName).delete(callback);
}
};
}
emit(eventName: string, args: any[] = []): any {
if (!this.#lookup.has(eventName)) {
return [];
}
let result = [];
for (const callback of this.#lookup.get(eventName)) {
result.push(callback(...args));
}
return result;
}
}