Here is the interview question prompt, presented for reference.
In modern applications, we often need asynchronous functions. These wait for responses from operations with unknown completion times. So many frameworks use an event-driven architecture.
Certain objects called emitters emit named events. This triggers listener functions to execute.
Each event has an ID. So listeners know which event to subscribe to. If that event fires, the listener is called.
Can you implement a class to enable this? It should:
For example:
// Create emitter
const emitter = new EventEmitter();
// Subscribe to event
emitter.subscribe('event1', callback1);
The emit method triggers events:
emitter.emit('event1', 1, 2);
This passes arguments to listeners.
const emitter = new EventEmitter();
emitter.subscribe('message', (msg) => {
console.log('Received message:', msg);
});
emitter.emit('message', 'Hello World!');
// Listener outputs:
// Received message: Hello World!
You can see the full challenge with visuals at this link.
Challenges • Asked over 3 years ago by Jake from AlgoDaily
This is the main discussion thread generated for Create Event Emitter (Main Thread).