File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time: subscribe: O(1)
2+ // unsubscribe: O(1)
3+ // emit: O(n)
4+ // Space: O(n)
5+
6+ type Callback = ( ...args : any [ ] ) => any ;
7+ type Subscription = {
8+ unsubscribe : ( ) => void
9+ }
10+
11+ class EventEmitter {
12+ #lookup: Map < string , Callback [ ] > ;
13+ constructor ( ) {
14+ this . #lookup = new Map < string , Callback [ ] > ( ) ;
15+ }
16+
17+ subscribe ( eventName : string , callback : Callback ) : Subscription {
18+ if ( ! this . #lookup. has ( eventName ) ) {
19+ this . #lookup. set ( eventName , [ ] ) ;
20+ }
21+ this . #lookup. get ( eventName ) . push ( callback ) ;
22+ return {
23+ unsubscribe : ( ) => {
24+ const i = this . #lookup. get ( eventName ) . indexOf ( callback ) ;
25+ if ( i !== - 1 ) {
26+ this . #lookup. get ( eventName ) . splice ( i , 1 ) ;
27+ }
28+ }
29+ } ;
30+ }
31+
32+ emit ( eventName : string , args : any [ ] = [ ] ) : any {
33+ if ( ! this . #lookup. has ( eventName ) ) {
34+ return [ ] ;
35+ }
36+ let result = [ ] ;
37+ for ( const listener of this . #lookup. get ( eventName ) ) {
38+ result . push ( listener ( ...args ) ) ;
39+ }
40+ return result ;
41+ }
42+ }
You can’t perform that action at this time.
0 commit comments