Event Emitter
JavaScript
medium
25 mins
Design and implement an EventEmitter class that mimics Node.js-style event handling.
It should support the following methods:
on(eventName, callback): Register a callback to be called every time the event is triggered.once(eventName, callback): Register a one-time callback (removed after first execution).off(eventName, callback): Remove a specific callback for an event.emit(eventName, ...args): Trigger all callbacks registered for that event with the given arguments.
Input: Method calls to the EventEmitter class.
Output: Appropriate invocations of callbacks.
Example Inputs & Outputs
const emitter = new EventEmitter(); const log = (...args) => console.log(...args); emitter.on('sayHello', log); emitter.emit('sayHello', 'Hi!'); // Output: Hi! emitter.once('sayBye', () => console.log('Bye!')); emitter.emit('sayBye'); // Output: Bye! emitter.emit('sayBye'); // No output emitter.off('sayHello', log); emitter.emit('sayHello', 'Hi again'); // No output
Constraints & Edge Cases
off()should not throw errors for unregistered callbacksemit()should handle no listeners gracefullyonce()handlers should auto-remove after one call- Multiple callbacks per event are allowed
- Callbacks should maintain argument order
Companies:
slack
shopify
flipkart
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
