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)
- Use an object to map event names to arrays of callbacks.
- subscribe pushes a callback and returns a function that filters it out.
- publish iterates the array and calls each callback with the data.
- subscribeOnce wraps subscribe — auto-unsubscribe after first call.
Topics
- Design Patterns
Asked at
Google · Slack · Microsoft
