Pub/Sub System

MediumDesign Patterns20 min4 tests

Implement a Publish/Subscribe messaging system.

Requirements

  • subscribe(event, callback) — register a callback for an event. Return an unsubscribe function.
  • publish(event, data) — trigger all callbacks registered for that event with the given data.
  • subscribeOnce(event, callback) — register a callback that fires only once.

Example

const ps = createPubSub();
ps.subscribe('msg', data => console.log(data));
ps.publish('msg', 'Hello!'); // logs 'Hello!'
Hints (4)
  1. Use an object to map event names to arrays of callbacks.
  2. subscribe pushes a callback and returns a function that filters it out.
  3. publish iterates the array and calls each callback with the data.
  4. subscribeOnce wraps subscribe — auto-unsubscribe after first call.

Topics

  • Design Patterns

Asked at

Google · Slack · Microsoft

Join Us
blur