Skip to content

Instantly share code, notes, and snippets.

@kutyel
Created July 14, 2021 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kutyel/bb090956f6d1b035d5d040ee58e72266 to your computer and use it in GitHub Desktop.
Save kutyel/bb090956f6d1b035d5d040ee58e72266 to your computer and use it in GitHub Desktop.
Github Copilot passed the Facebook EventEmitter JavaScript test... Yikes!
/**
*
* 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