← Snowflake Interview Insights
Start by clarifying requirements and edge cases, then outline the data structure (e.g., a Map of event names to arrays of listener objects) and implement each method with careful handling of once and off during emit. Discuss trade-offs like error handling, memory management, and performance considerations.
Pro tip: Mention that you would iterate over a copy of the listeners array during emit to avoid issues when listeners are added or removed mid-emit, and consider using a Set for O(1) removal if order isn't critical.
Ask about expected behavior: should emit be synchronous? How to handle errors in listeners? Should off remove all listeners for an event? This shows you think about edge cases.
Choose a Map or object to store event names as keys and arrays of listener objects (with callback and once flag) as values. Explain why this supports efficient add/remove.
Write on, off, emit, and once. For once, wrap the callback to automatically remove itself after invocation. In emit, iterate over a copy of the listeners to avoid mutation issues.
Address scenarios like emitting an event with no listeners, removing a listener during emit, and ensuring once listeners are removed even if the callback throws.
Talk about synchronous vs asynchronous emit, memory leak prevention, and potential extensions like wildcard events or max listeners warning.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.