Building an Event Notifier in JavaScript: Optimizing Handler Registration and Removal

Last week, I was asked to build an event notifier in JavaScript during an interview: Requirements were straightforward: - create an on(eventName, handler) method - return a remover (unsubscribe) function from on - create a send(eventName, ...args) method - call all handlers registered for that event with the given arguments My initial approach: - maintained an events object - stored handlers in an array against each event name - used a unique id(leveraging Symbol) inside the remover’s closure to de-register the handler - send() simply looped over the handlers and invoked them with arguments That solved correctness. Follow-up question was about optimization. To improve add/remove performance, I replaced the array with a Map, which made handler registration and removal more efficient. Sharing my implementation here — happy to hear suggestions or alternate ways you’d approach this. Always open to learning. 🙂 #javascript #machinecoding #interviewprep #frontend #learninpublic #codinginterviews

  • text

To view or add a comment, sign in

Explore content categories