MediumPro challengeJavaScriptTypeScript

Event Bus (Pub/Sub)

Node.jsDesign

Implement createEventBus() with:

  • subscribe(event, listener) — register a listener, returns an unsubscribe function.
  • publish(event, data) — call all listeners for the event with data.

solve drives your bus through a sequence of operations and returns
the call log: [[subscriberId, data], ...].

Operations:

  • ['subscribe', event, id] — subscribe listener id to event
  • ['publish', event, data] — publish data to event
  • ['unsubscribe', id] — call the unsubscribe function returned for id

Sample tests

Test #1Publish with no subscribers
Input: [[["publish","news","nothing"]]]
Output: []
Test #2Two separate events
Input: [[["subscribe","a","s1"],["subscribe","b","s2"],["publish","a",1],["publish","b",2]]]
Output: [["s1",1],["s2",2]]
Test #3Two subscribers to same event
Input: [[["subscribe","e","s1"],["subscribe","e","s2"],["publish","e",42]]]
Output: [["s1",42],["s2",42]]
Test #4Basic subscribe+publish
Input: [[["subscribe","news","s1"],["publish","news","hello"]]]
Output: [["s1","hello"]]
Test #5Unsubscribe stops delivery
Input: [[["subscribe","news","s1"],["publish","news","hello"],["unsubscribe","s1"],["publish","news","world"]]]
Output: [["s1","hello"]]