Skip to content

Instantly share code, notes, and snippets.

@kutyel
Last active October 11, 2020 17:31
Show Gist options
  • Save kutyel/7d8f204a347840a6ee7220743957e504 to your computer and use it in GitHub Desktop.
Save kutyel/7d8f204a347840a6ee7220743957e504 to your computer and use it in GitHub Desktop.
Question for my Frontend Interview at Facebook
/*
* Create an event emitter that goes like this
* emitter = new Emitter();
*
* Allows you to subscribe to some event
* sub1 = emitter.subscribe('function_name', callback1);
* (you can have multiple callbacks to the same event)
* sub2 = emitter.subscribe('function_name', callback2);
*
* You can emit the event you want with this api
* (you can receive 'n' number of arguments)
* sub1.emit('function_name', foo, bar);
*
* And allows you to release the subscription like this
* (but you should be able to still emit from sub2)
* sub1.release();
*/
class Emitter {
constructor(events = {}) {
this.events = events
}
subscribe(name, cb) {
(this.events[name] || (this.events[name] = [])).push(cb)
return {
release: () => this.events[name] &&
this.events[name].splice(this.events[name].indexOf(cb) >>> 0, 1)
}
}
emit(name, ...args) {
return (this.events[name] || []).map(fn => fn(...args))
}
}
export default Emitter
const expect = require('expect')
const Emitter = require('./facebook')
// Step 1
let test = 0
const emitter = new Emitter()
emitter.emit('sum', 1)
expect(test).toBe(0) // should trigger nothing
const sub1 = emitter.subscribe('sum', num => (test = test + num))
emitter.emit('sum', 1)
expect(test).toBe(1) // should trigger 1 callback
const sub2 = emitter.subscribe('sum', num => (test = test * num))
emitter.emit('sum', 2)
expect(test).toBe(6) // should trigger 2 callbacks
// Step 2
sub1.release()
emitter.emit('sum', 3)
expect(test).toBe(18) // should trigger 1 callback
// 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!!! 👏🏼 👏🏼 👏🏼')
@RamAnbalagan
Copy link

Good one!

@im6
Copy link

im6 commented Oct 21, 2019

thanks for this solution. could you please explain a little about why use indexOf(cb) >>> 0 ? I am a little confused about it

@jurnalanas
Copy link

thanks for this solution. could you please explain a little about why use indexOf(cb) >>> 0 ? I am a little confused about it

to prevent a negative number

@gilib7
Copy link

gilib7 commented Apr 17, 2020

Hi Kutyel,
why did you add "return" in release and emit?
is class is the scope of the "this" of the release function? or is it because the subscribe?

thanks

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