KatInterview

Process Event Listener Operations

Data Structure DesignAuto-graded · 15 test cases
MediumAuto-gradedData Structure Designobserver-patterndata-structuresstate-management

Last updated

Tests understanding of the observer pattern through ordered listener management, callback registration/removal, and event dispatch simulation.

You are building a system that tracks event listener registrations and dispatches. Given a sequence of operations on an event system, simulate the behavior and return the results.

Your function receives two parallel lists:

  • operations: a list of operation names ("on", "off", or "emit")
  • arguments: corresponding arguments for each operation

Operations:

  1. on(event_name, listener_id): Register a listener (identified by a string or number) for the given event name. If the same listener is registered multiple times, it should trigger multiple times when the event fires. Listeners fire in the order they were registered.

  2. off(event_name, listener_id): Unregister one instance of the specified listener for the given event. If the listener was registered multiple times, only the first registration is removed. If the listener was never registered or the event doesn't exist, this is a no-op.

  3. emit(event_name, *args): Trigger all listeners registered for the event, passing any additional arguments. Return a list of invocations in registration order, where each invocation is [listener_id, args_list]. If no listeners are registered for the event, return an empty list.

Return Value:

A list with one entry per operation:

  • on and off operations return None
  • emit operations return a list of [listener_id, arguments] pairs representing each listener invocation in order

Constraints:

  • 1 ≤ len(operations) ≤ 1000
  • Event names are always strings
  • Listener identifiers can be strings or integers
  • emit can have 0 or more additional arguments beyond the event name
  • Operations on different event names are independent

Examples

Example 1

Input: process_event_operations(['on', 'emit', 'off', 'emit'], [['greet', 'greet'], ['greet', 'Alice'], ['greet', 'greet'], ['greet', 'Bob']])

Output: [None, [['greet', ['Alice']]], None, []]

Example 2

Input: process_event_operations(['on', 'on', 'emit', 'off', 'emit'], [['update', 'a'], ['update', 'b'], ['update', 1, 2], ['update', 'a'], ['update', 3]])

Output: [None, None, [['a', [1, 2]], ['b', [1, 2]]], None, [['b', [3]]]]

Example 3

Input: process_event_operations(['emit', 'off', 'on', 'emit'], [['missing', 1], ['x', 'f'], ['x', 'f'], ['x']])

Output: [[], None, None, [['f', []]]]

Hints

Hint 1

Store listeners for each event in a list to preserve registration order

Hint 2

Use dictionary.get() with a default empty list to handle events that don't exist yet

Hint 3

The remove() method on a list only removes the first matching element, which gives you the correct behavior for off