File tree 1 file changed +58
-0
lines changed
1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 2694. Event Emitter
2
+ // URL -> https://leetcode.com/problems/event-emitter
3
+
4
+ class EventEmitter {
5
+ constructor ( ) {
6
+ this . eventRecords = { }
7
+ }
8
+ /**
9
+ * @param {string } eventName
10
+ * @param {Function } callback
11
+ * @return {Object }
12
+ */
13
+ subscribe ( eventName , callback ) {
14
+ if ( ! this . eventRecords . hasOwnProperty ( eventName ) ) {
15
+ this . eventRecords [ eventName ] = [ ]
16
+ }
17
+
18
+ let cbList = this . eventRecords [ eventName ]
19
+ cbList . push ( callback ) ;
20
+
21
+ return {
22
+ unsubscribe : ( ) => {
23
+ const index = cbList . indexOf ( callback )
24
+ cbList . splice ( index , 1 )
25
+ }
26
+ } ;
27
+ }
28
+
29
+ /**
30
+ * @param {string } eventName
31
+ * @param {Array } args
32
+ * @return {Array }
33
+ */
34
+ emit ( eventName , args = [ ] ) {
35
+ if ( ! this . eventRecords . hasOwnProperty ( eventName ) ) {
36
+ return [ ]
37
+ }
38
+ let result = [ ]
39
+ let cbList = this . eventRecords [ eventName ]
40
+
41
+ for ( let cb of cbList ) {
42
+ result . push ( cb ( ...args ) )
43
+ }
44
+ return result
45
+ }
46
+ }
47
+
48
+ /**
49
+ * const emitter = new EventEmitter();
50
+ *
51
+ * // Subscribe to the onClick event with onClickCallback
52
+ * function onClickCallback() { return 99 }
53
+ * const sub = emitter.subscribe('onClick', onClickCallback);
54
+ *
55
+ * emitter.emit('onClick'); // [99]
56
+ * sub.unsubscribe(); // undefined
57
+ * emitter.emit('onClick'); // []
58
+ */
You can’t perform that action at this time.
0 commit comments