Implement Event Emitter
MediumDesign Patterns20 min4 tests
Implement an EventEmitter class with subscribe/unsubscribe/emit functionality.
Requirements
on(event, callback)- Subscribe to an eventoff(event, callback)- Unsubscribe from an eventemit(event, ...args)- Trigger all callbacks for an eventonce(event, callback)- Subscribe for only one invocation
Example
const emitter = new EventEmitter();
emitter.on('greet', (name) => console.log(`Hello, ${name}!`));
emitter.emit('greet', 'World'); // "Hello, World!"Hints (5)
- Use a Map to store event names and their callback arrays.
- For
on, push the callback to the array for that event. - For
off, find and remove the specific callback from the array. - For
emit, iterate through all callbacks and invoke them with the args. - For
once, create a wrapper that callsoffbefore invoking the original callback.
Topics
- Design Patterns
Asked at
Meta · Google · Microsoft · Shopify
