mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems(js): add “2694. Event Emitter”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
0a4eda37ee
commit
efeafcae88
1 changed files with 39 additions and 0 deletions
39
problems/js/event-emitter.js
Normal file
39
problems/js/event-emitter.js
Normal file
|
@ -0,0 +1,39 @@
|
|||
class EventEmitter {
|
||||
constructor() {
|
||||
this.mapping = new Map();
|
||||
}
|
||||
|
||||
subscribe(event, cb) {
|
||||
if (!this.mapping.has(event)) {
|
||||
this.mapping.set(event, new Array());
|
||||
}
|
||||
|
||||
this.mapping.get(event).push(cb);
|
||||
|
||||
return {
|
||||
unsubscribe: () => {
|
||||
this.mapping.set(event, this.mapping.get(event).filter(s => s !== cb));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
emit(event, args = []) {
|
||||
if (!this.mapping.has(event)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.mapping.get(event).map(cb => cb(...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'); // []
|
||||
*/
|
Loading…
Reference in a new issue