MediumPro challengePythonJavaScriptTypeScript

Pub/Sub Event Bus

PatternsEventsObjects

Implement an EventBus class with:

  • on(event, handler) — subscribe. Returns an unsubscribe function.
  • emit(event, ...args) — call all handlers for the event.
  • off(event, handler) — remove a specific handler.

solve(ops) replays operations and returns all emissions captured.

Sample tests

Test #1Unsubscribe before emit → nothing captured
Input: [[{"id":"h1","type":"on","event":"a"},{"id":"h1","type":"off","event":"a"},{"args":[],"type":"emit","event":"a"}]]
Output: []
Test #2Two listeners on same event
Input: [[{"id":"h1","type":"on","event":"x"},{"id":"h2","type":"on","event":"x"},{"args":["hello"],"type":"emit","event":"x"}]]
Output: [{"args":["hello"],"event":"x"},{"args":["hello"],"event":"x"}]
Test #3Emit on event with no listeners
Input: [[{"args":[],"type":"emit","event":"missing"}]]
Output: []
Test #4Off between two emits
Input: [[{"id":"h1","type":"on","event":"a"},{"args":[1],"type":"emit","event":"a"},{"id":"h1","type":"off","event":"a"},{"args":[2],"type":"emit","event":"a"}]]
Output: [{"args":[1],"event":"a"}]
Test #5Subscribe then emit
Input: [[{"id":"h1","type":"on","event":"click"},{"args":[1],"type":"emit","event":"click"}]]
Output: [{"args":[1],"event":"click"}]