Implement Custom EventEmitter (Pub/Sub Pattern)
Problem Statement
Implement a custom `EventEmitter` class supporting `on(event, listener)`, `off(event, listener)`, `emit(event, ...args)`, and `once(event, listener)`. Ensure unsubscribing works reliably and listeners do not leak.
Target Complexity
Time:
O(1) on, O(N) emit and off
Space:
O(N) listener storage
Interview Talking Points:
- • Explain snapshot iteration (`[...listeners]`) to avoid infinite loops if a listener unsubscribes or subscribes inside its own callback.
- • Discuss memory leak prevention via returning unsubscribe teardown callbacks.
Solution Editor (JavaScript)
Ready to run
Test Results
Subscribes, emits with arguments, and unsubscribes correctly
Test #1once() listener fires exactly once then auto-unsubscribes
Test #2