Skip to content

Instantly share code, notes, and snippets.

@kutyel
Last active August 11, 2017 12:34
Show Gist options
  • Save kutyel/6ce094460d2a298ab6146d11363468ac to your computer and use it in GitHub Desktop.
Save kutyel/6ce094460d2a298ab6146d11363468ac to your computer and use it in GitHub Desktop.
JavaScript Code Challenge: make your own custom Emitter! (Note: you need to have Node >= 6.4.0)

JavaScript Interview Test

Node version

Fork this gist and submit a link with your solution

Usage

First, install globally expect (you need it to test your code):

npm install -global expect

Then, whenever you are done, simply do the following to know if you passed (or failed):

$ node ./test.js

FIRST STEP

Create an event emitter that goes like this:

const emitter = new Emitter();

Its instance allows you to subscribe to some event by passing a callback function

emitter.subscribe('myEvent', firstArgument => console.log('a callback!'));

...any times you want...

emitter.subscribe('myEvent', (firstArgument, secondArgument) => console.log('another callback!'));

You can emit the event you want and pass any number of arguments

emitter.emit('myEvent', 'firstArgument', 'secondArgument');

SECOND STEP

Make the return from the subscribe method to return a function that allows you to release that subscription:

const sub1 = emitter.subscribe('myEvent', () => console.log('a callback!'));
sub1();

...but all other subscriptions shall remain intact

THIRD STEP

Make the emit method return an array with every return value for each subscription callback


Good luck! πŸ’ͺ🏼πŸ’ͺ🏼πŸ’ͺ🏼

class Emitter {
constructor() { }
}
module.exports = Emitter
const expect = require('expect');
const Emitter = require('./Emitter');
// Step 1
let test = 0;
const emitter = new Emitter();
emitter.emit('sum', 1); // should trigger nothing
expect(test).toBe(0);
const sub1 = emitter.subscribe('sum', num => test = test + num);
emitter.emit('sum', 1); // should trigger 1 callback
expect(test).toBe(1);
const sub2 = emitter.subscribe('sum', num => test = test * num);
emitter.emit('sum', 2); // should trigger 2 callbacks
expect(test).toBe(6);
// Step 2
sub1();
emitter.emit('sum', 3); // should trigger 1 callback
expect(test).toBe(18);
// Step 3
const myEvent1 = emitter.subscribe('myEvent', () => 1);
const myEvent2 = emitter.subscribe('myEvent', () => 2);
const myEvent3 = emitter.subscribe('myEvent', () => true);
const result = emitter.emit('myEvent');
expect(result).toEqual([1, 2, true]);
console.info('You passed the test!!! πŸ‘πŸΌ πŸ‘πŸΌ πŸ‘πŸΌ');
@aarongarciah
Copy link

I'd still rather prefer to make an npm install of local dependencies than a global npm install of a package :P

@kutyel
Copy link
Author

kutyel commented Aug 11, 2017

That is because you are such a hipster 😜

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment