Implement an EventEmitter with on, off and emit that returns callback results

Quick Overview

Implement an EventEmitter class with on, off and emit, where callbacks are named by string keys and emit returns each callback's result in registration order. It tests picking a per-event structure that keeps order and repeated registrations, removing only the first matching registration, and handling empty argument lists.

Implement an EventEmitter with on, off and emit that returns callback results

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design and implement an `EventEmitter` class that lets callers subscribe callbacks to named events, unsubscribe them, and emit an event to run every callback registered for it. The emitter must support several callbacks for the same event. When an event is emitted, its callbacks run in the order they were registered, each receiving the arguments passed to `emit`, and `emit` returns a list of their results. If no callbacks are registered for the event, `emit` returns an empty list. Callbacks are identified by string keys that map to predefined behaviors: - `"sum"` returns the sum of all arguments. - `"product"` returns the product of all arguments. - `"count"` returns the number of arguments. - `"first"` returns the first argument, or `None` if there are no arguments. - `"negate_first"` returns the negation of the first argument, or `0` if there are no arguments. Implement the following methods: - `on(event: str, callback_key: str) -> None` registers the callback named by `callback_key` for `event`. The same key can be registered multiple times. - `off(event: str, callback_key: str) -> None` removes the first occurrence of `callback_key` from the event's listener list. If the key is not registered for that event, it does nothing. - `emit(event: str, args: List[int]) -> List[Optional[int]]` emits the event with the given arguments, calls every registered callback in order, and returns their results. It returns an empty list when no callbacks are registered. A result is `None` only when `"first"` runs with no arguments. Example 1: ```text Input: ["EventEmitter", "on", "on", "emit", "off", "emit"] [[], ["click", "sum"], ["click", "count"], ["click", [1, 2, 3]], ["click", "sum"], ["click", [4, 5]]] Output: [null, null, null, [6, 3], null, [2]] emitter = EventEmitter() emitter.on("click", "sum") emitter.on("click", "count") emitter.emit("click", [1, 2, 3]) # [6, 3] (sum = 6, count = 3) emitter.off("click", "sum") emitter.emit("click", [4, 5]) # [2] (only count remains) ``` The first emit runs `"sum"` and then `"count"` in registration order. After `off` removes `"sum"`, only `"count"` is left, and it sees two arguments. Example 2: ```text Input: ["EventEmitter", "emit", "on", "emit", "off", "emit"] [[], ["data", [10]], ["data", "first"], ["data", [10, 20]], ["data", "first"], ["data", [10, 20]]] Output: [null, [], null, [10], null, []] emitter = EventEmitter() emitter.emit("data", [10]) # [] (no callbacks registered) emitter.on("data", "first") emitter.emit("data", [10, 20]) # [10] (first argument is 10) emitter.off("data", "first") emitter.emit("data", [10, 20]) # [] (no callbacks left) ``` An emit on an event with no callbacks returns an empty list, and removing the only callback returns the event to that state. ```hint Choosing the container Two requirements decide the per-event container: registration order must be kept, and the same key may appear more than once. Check which standard structures satisfy both. ``` ```hint Empty inputs Before writing `emit`, work out what each of the five behaviors returns for `args = []`, and what `off` and `emit` should do for an event that was never registered. ``` ### Constraints & Assumptions - Event names are non-empty strings. - Callback keys are always one of `"sum"`, `"product"`, `"count"`, `"first"`, `"negate_first"`. - The same callback key can be registered multiple times for the same event. - `off` removes only the first occurrence of the given key. - Arguments passed to `emit` are lists of integers. - At most 1,000 operations are performed. ### Clarifying Questions to Ask - If `on` ever receives a key outside the five predefined behaviors, should it raise an error or ignore the call? - What should `"product"` return for an empty argument list, and is `None` acceptable in the result list when `"first"` gets no arguments? - With at most 1,000 operations, is a linear scan in `off` acceptable, or is faster removal expected? ### What a Strong Answer Covers - A per-event container that keeps registration order and allows repeated keys, with a reason for the choice. - The exact semantics of `off`: which registration it removes, what happens to the order of the rest, and what it does for unknown events or keys. - The result of every behavior on an empty argument list, and a return type that matches those results. - The time and space cost of `on`, `off` and `emit`. - How the behavior lookup is kept apart from the listener lists, so a new behavior does not require changes to `on`, `off` or `emit`. ### Follow-up Questions - How would you change the design to accept real callback functions instead of string keys, and how would `off` decide which registration to remove? - If a callback could call `on` or `off` on the same event while `emit` is running, what should the current emit see, and how would you implement that? - How would you add a `once(event, callback_key)` method whose callback runs on the next emit only? - If one event had tens of thousands of listeners and `off` were called often, how would you make removal faster than a linear scan while keeping the order?

Overview: Implement an EventEmitter class with on, off and emit, where callbacks are named by string keys and emit returns each callback's result in registration order. It tests picking a per-event structure that keeps order and repeated registrations, removing only the first matching registration, and handling empty argument lists.

General logo
General
Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design and implement an EventEmitter class that lets callers subscribe callbacks to named events, unsubscribe them, and emit an event to run every callback registered for it.

The emitter must support several callbacks for the same event. When an event is emitted, its callbacks run in the order they were registered, each receiving the arguments passed to emit, and emit returns a list of their results. If no callbacks are registered for the event, emit returns an empty list.

Callbacks are identified by string keys that map to predefined behaviors:

  • "sum" returns the sum of all arguments.
  • "product" returns the product of all arguments.
  • "count" returns the number of arguments.
  • "first" returns the first argument, or None if there are no arguments.
  • "negate_first" returns the negation of the first argument, or 0 if there are no arguments.

Implement the following methods:

  • on(event: str, callback_key: str) -> None registers the callback named by callback_key for event . The same key can be registered multiple times.
  • off(event: str, callback_key: str) -> None removes the first occurrence of callback_key from the event's listener list. If the key is not registered for that event, it does nothing.
  • emit(event: str, args: List[int]) -> List[Optional[int]] emits the event with the given arguments, calls every registered callback in order, and returns their results. It returns an empty list when no callbacks are registered. A result is None only when "first" runs with no arguments.

Example 1:

Input:
["EventEmitter", "on",             "on",               "emit",               "off",            "emit"]
[[],             ["click", "sum"], ["click", "count"], ["click", [1, 2, 3]], ["click", "sum"], ["click", [4, 5]]]

Output: [null, null, null, [6, 3], null, [2]]

emitter = EventEmitter()
emitter.on("click", "sum")
emitter.on("click", "count")
emitter.emit("click", [1, 2, 3])   # [6, 3]  (sum = 6, count = 3)
emitter.off("click", "sum")
emitter.emit("click", [4, 5])      # [2]     (only count remains)

The first emit runs "sum" and then "count" in registration order. After off removes "sum", only "count" is left, and it sees two arguments.

Example 2:

Input:
["EventEmitter", "emit",         "on",              "emit",             "off",             "emit"]
[[],             ["data", [10]], ["data", "first"], ["data", [10, 20]], ["data", "first"], ["data", [10, 20]]]

Output: [null, [], null, [10], null, []]

emitter = EventEmitter()
emitter.emit("data", [10])         # []    (no callbacks registered)
emitter.on("data", "first")
emitter.emit("data", [10, 20])     # [10]  (first argument is 10)
emitter.off("data", "first")
emitter.emit("data", [10, 20])     # []    (no callbacks left)

An emit on an event with no callbacks returns an empty list, and removing the only callback returns the event to that state.

Constraints & Assumptions

  • Event names are non-empty strings.
  • Callback keys are always one of "sum" , "product" , "count" , "first" , "negate_first" .
  • The same callback key can be registered multiple times for the same event.
  • off removes only the first occurrence of the given key.
  • Arguments passed to emit are lists of integers.
  • At most 1,000 operations are performed.

Clarifying Questions to Ask Guidance

  • If on ever receives a key outside the five predefined behaviors, should it raise an error or ignore the call?
  • What should "product" return for an empty argument list, and is None acceptable in the result list when "first" gets no arguments?
  • With at most 1,000 operations, is a linear scan in off acceptable, or is faster removal expected?

What a Strong Answer Covers Guidance

  • A per-event container that keeps registration order and allows repeated keys, with a reason for the choice.
  • The exact semantics of off : which registration it removes, what happens to the order of the rest, and what it does for unknown events or keys.
  • The result of every behavior on an empty argument list, and a return type that matches those results.
  • The time and space cost of on , off and emit .
  • How the behavior lookup is kept apart from the listener lists, so a new behavior does not require changes to on , off or emit .

Follow-up Questions Guidance

  • How would you change the design to accept real callback functions instead of string keys, and how would off decide which registration to remove?
  • If a callback could call on or off on the same event while emit is running, what should the current emit see, and how would you implement that?
  • How would you add a once(event, callback_key) method whose callback runs on the next emit only?
  • If one event had tens of thousands of listeners and off were called often, how would you make removal faster than a linear scan while keeping the order?