-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.ts
37 lines (33 loc) · 1023 Bytes
/
Solution.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
type Callback = (...args: any[]) => any;
type Subscription = {
unsubscribe: () => void;
};
class EventEmitter {
private d: Map<string, Set<Callback>> = new Map();
subscribe(eventName: string, callback: Callback): Subscription {
this.d.set(eventName, (this.d.get(eventName) || new Set()).add(callback));
return {
unsubscribe: () => {
this.d.get(eventName)?.delete(callback);
},
};
}
emit(eventName: string, args: any[] = []): any {
const callbacks = this.d.get(eventName);
if (!callbacks) {
return [];
}
return [...callbacks].map(callback => callback(...args));
}
}
/**
* const emitter = new EventEmitter();
*
* // Subscribe to the onClick event with onClickCallback
* function onClickCallback() { return 99 }
* const sub = emitter.subscribe('onClick', onClickCallback);
*
* emitter.emit('onClick'); // [99]
* sub.unsubscribe(); // undefined
* emitter.emit('onClick'); // []
*/