Created
July 14, 2021 09:25
-
-
Save kutyel/bb090956f6d1b035d5d040ee58e72266 to your computer and use it in GitHub Desktop.
Github Copilot passed the Facebook EventEmitter JavaScript test... Yikes!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* Create an event emitter that goes like this: | |
* | |
```javascript | |
const emitter = new Emitter(); | |
``` | |
Its instance allows you to subscribe to some event by passing a callback function | |
```javascript | |
emitter.subscribe('myEvent', firstArgument => console.log('a callback!')); | |
``` | |
...any times you want... | |
```javascript | |
emitter.subscribe('myEvent', (firstArgument, secondArgument) => console.log('another callback!')); | |
``` | |
You can emit the event you want and pass any number of arguments | |
```javascript | |
emitter.emit('myEvent', 'firstArgument', 'secondArgument'); | |
``` | |
* Make the return from the subscribe method to return a function that allows you to release that subscription: | |
```javascript | |
const sub1 = emitter.subscribe('myEvent', () => console.log('a callback!')); | |
sub1(); | |
``` | |
...but all other subscriptions shall remain intact. | |
* Make the emit method return an array with every return value for each subscription callback. | |
*/ | |
export default class EventEmitter { | |
constructor() { | |
this.subscriptions = {}; | |
} | |
subscribe(event, callback) { | |
if (!this.subscriptions[event]) { | |
this.subscriptions[event] = []; | |
} | |
this.subscriptions[event].push(callback); | |
return () => { | |
const index = this.subscriptions[event].indexOf(callback); | |
this.subscriptions[event].splice(index, 1); | |
}; | |
} | |
emit(event, ...args) { | |
if (!this.subscriptions[event]) { | |
return []; | |
} | |
return this.subscriptions[event].map((subscription) => | |
subscription(...args) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment