Exercício de event emitter em Javascript usando TDD
Esse é um exercício de uma entrevista técnica de emprego para vaga de Engenheiro de Software. Então você pode utilizá-la para treinar seus conhecimentos antes de uma entrevista javascript.
Para fazer o exercício você terá que instalar o Yarn em sua máquina e estar levemente familiarizado com o desenvolvimento de software orientado a testes (TDD).
Baixe a pasta “exercise-event-emitter-master” e tente solucioná-lo antes de ver a resposta. Procure se focar mais em solucionar o problema do que em eficiência.
Lembre-se: Sempre há mais de uma maneira de se chegar na resposta correta. E o mais importante se divirta!
The goal of this exercise is to create an event emitter which can listen, unlisten and emit events.
The main module exports an object with a create method which act as a factory and should return a new event emitter every time it is called. The implementation of the emitter itself is up to you.
By executing the package.json test script, a jest process will start and re-run the test suite after every file change you made.
import Emitter from './emitter.js' const emitter = Emitter.create() const handleMyEvent = () => { console.log('Hello!') } // Registers the callback `handleMyEvent` to be called when we call emitter.emit passing `myEvent` as parameter emitter.on('myEvent', handleMyEvent) // This will call the `handleMyEvent` function emitter.emit('myEvent') // Will print "Hello!" // Unregisters the callback `handleMyEvent` emitter.off('myEvent', handleMyEvent) // No function will be called since `myEvent` does not have any callbacks assigned to it anymore emitter.emit('myEvent')const EventEmitter = require('...') // Return a new event emitter const emitter = EventEmitter.create()
on(event: string, callback: function): function
Registers a callback that runs when event is emitted.
Example:
emitter.on('click', () => { console.log('Click!') }) // register a new listener for the 'click' eventIt returns a method which unregisters the listener:
Example:
const cancel = emitter.on('click', () => { console.log('Click!') }) cancel() // unregister the click listener
off(event: string, callback: function)
Unregisters a callback from the event callback list.
Example:
const callback = () => { console.log('Click!') } // register the listener emitter.on('click', callback) // unregister the listener emitter.off('click', callback)
emit(event: string, data: object)
Execute all callbacks registered for event passing data as a parameter.
Example:
emitter.on('click', () => console.log('Click 1')) emitter.on('click', () => console.log('Click 2')) emitter.on('click', () => console.log('Click 3')) emitter.emit('click') // Prints: // Click 1 // Click 2 // Click 3Every listener callback receives a data object which contains the type of the event and any other property passed on .emit():
Example:
emitter.on('loaded', e => console.log(e)) emitter.emit('loaded', { foo: 'potato' }) // Prints: // { type: 'loaded', foo: 'potato' }
once(event: string, callback: function): function
Registers a callback tha runs only once when event is emitted.
Example:
emitter.once('click', () => console.log('Single click!')) emitter.emit('click') emitter.emit('click') // Prints 'Single click!' only once
race(Array<[event: string, callback: function]>): function
Receives a list of [event, callback] and when any of the passed events is emitted, it unregisters all of them.
Example:
emitter.race([ ['success', () => console.log('Success!')], ['failure', () => console.log('Failure :(')], ]) emitter.emit('success') // Prints 'Success!', `success` and `failure` are unregistered. emitter.emit('failure') // nothing happens