Grammarly Coding Interview Question: Implement a Basic Pub/Sub System

19 Views
No Comments

You can select any programming language.

Implement a basic Pub/Sub following the given interface.

// Interface
interface Subscription {unsubscribe(): void
}

interface Subject<T> {publish(value: T): void
  subscribe(cb: (value: T) => void): Subscription
}

// Usage

const subject = new Subject()
const subscription1 = subject.subscribe(x => console.log(x))
const subscription2 = subject.subscribe(x => console.log(x + 10))

subject.publish(1) // prints 1 and 11 in any order

subscription1.unsubscribe()

This problem asks you to build a basic Pub/Sub system that keeps track of subscribers, supports publishing values to all active callbacks, and allows each subscription to be removed later through an unsubscribe method. The key implementation detail is managing subscriber storage and ensuring that publish() invokes every current listener, while unsubscribe() correctly detaches only the matching callback. Since the output order is not important, the main challenge is designing a clean, reliable subscription lifecycle rather than ordering logic.

END
 0