MediumPro challengePythonJavaScriptTypeScript

Event Emitter

PatternsFunctionsNode

Implement an EventEmitter class with three methods:

  • on(event, handler) — subscribe.
  • off(event, handler) — unsubscribe a previously-registered handler.
  • emit(event, ...args) — invoke every handler registered for event,

passing the extra arguments through, in registration order.

Edge cases

  • Emitting an event with no handlers must be a no-op (no throw).
  • Calling off for a handler that isn't registered must be a no-op.
  • A handler may unsubscribe itself or another from inside emit

the in-flight emit must still complete its current iteration safely.

The harness's solve(operations) drives your implementation through a
sequence of ['on'|'off'|'emit', ...] tuples and records the order in which
handlers fire.

Sample tests

Test #1Different events stay isolated
Input: [[["on","a","h1"],["on","b","h2"],["emit","a",1],["emit","b",2,3],["off","a","h1"],["emit","a",99]]]
Output: [["h1",[1]],["h2",[2,3]]]
Test #2Single handler, single emit
Input: [[["on","click","h1"],["emit","click","a"]]]
Output: [["h1",["a"]]]
Test #3Two handlers fire in registration order
Input: [[["on","click","h1"],["on","click","h2"],["emit","click","x"]]]
Output: [["h1",["x"]],["h2",["x"]]]
Test #4off prevents the next emit from firing
Input: [[["on","click","h1"],["off","click","h1"],["emit","click","x"]]]
Output: []
Test #5Emit with no listeners is a no-op
Input: [[["emit","noop","a"]]]
Output: []