Skip to content

Commit 0f94269

Browse files
authored
Create event-emitter.ts
1 parent 4a3cb6e commit 0f94269

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

TypeScript/event-emitter.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}

0 commit comments

Comments
 (0)