-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02694-event-emitter.ts
54 lines (46 loc) · 1.46 KB
/
02694-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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* medium :: typescript */
/*
A custom EventEmitter class that allows subscribing to events and emitting them.
- - - -
Time :: O(1) :: 70ms
Space :: O(N) :: 52.04MB
*/
type Callback = ( ...args: any[] ) => any;
type Subscription = {
unsubscribe: () => void
};
// Solution entrypoint :: - - - -
class EventEmitter
{
private _subs: Record<string, Set<Callback>> = {};
// Subscribe to an event with a callback function :
subscribe( eventName: string, callback: Callback ): Subscription
{
let set = this._subs[eventName];
if ( !set )
{
this._subs[eventName] = set = new Set();
}
set.add( callback );
// Return an object with an unsubscribe method to remove the callback :
return {
unsubscribe: () => {
set.delete( callback );
}
};
}
// Emit an event, calling all the subscribed callbacks :
emit( eventName: string, args: any[] = [] ): any
{
const result: any[] = [];
const set = this._subs[eventName];
if ( set )
{
set.forEach( ( fn ) => {
result.push( fn( ...args ) );
} );
}
return result;
}
}
// End. :: - - - -