-
Notifications
You must be signed in to change notification settings - Fork 0
/
2694-event-emitter.ts
60 lines (53 loc) · 2.77 KB
/
2694-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
55
56
57
58
59
60
// Title: Event Emitter
// Description:
// Design an EventEmitter class. This interface is similar (but with some differences) to the one found in Node.js or the Event Target interface of the DOM.
// The EventEmitter should allow for subscribing to events and emitting them.
// Your EventEmitter class should have the following two methods:
// subscribe -
// This method takes in two arguments: the name of an event as a string and a callback function.
// This callback function will later be called when the event is emitted.
// An event should be able to have multiple listeners for the same event.
// When emitting an event with multiple callbacks, each should be called in the order in which they were subscribed. An array of results should be returned.
// You can assume no callbacks passed to subscribe are referentially identical.
// The subscribe method should also return an object with an unsubscribe method that enables the user to unsubscribe.
// When it is called, the callback should be removed from the list of subscriptions and undefined should be returned.
// emit -
// This method takes in two arguments: the name of an event as a string and an optional array of arguments that will be passed to the callback(s).
// If there are no callbacks subscribed to the given event, return an empty array.
// Otherwise, return an array of the results of all callback calls in the order they were subscribed.
// Link: https://leetcode.com/problems/event-emitter/
type Callback = (...args: any[]) => any;
type Subscription = {
unsubscribe: () => void
};
class EventEmitter {
readonly subscriberBuckets: Map<string, Set<Callback>> = new Map();
subscribe(eventName: string, callback: Callback): Subscription {
if (!this.subscriberBuckets.has(eventName)) this.subscriberBuckets.set(eventName, new Set());
this.subscriberBuckets.get(eventName).add(callback);
return {
unsubscribe: () => {
this.subscriberBuckets.get(eventName).delete(callback);
}
};
}
emit(eventName: string, args: any[] = []): any {
/*
The iteration over a Set visits elements in insertion order.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#iterating_sets
*/
return Array.from(this.subscriberBuckets.get(eventName) ?? [])
.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'); // []
*/