Skip to the solution
EasyFrontendAsked in 20246 min read

Pub-Sub topic structures

3.5k views

The problem

Problem, as an interviewer would state it: "Build a Pub-Sub system — subscribe(topic, handler) and publish(topic, data). Multiple things can subscribe to the same topic, and subscribing should give back a way to unsubscribe later."

Examples:

Code
const unsub = bus.subscribe("user:login", (data) => console.log(data));
bus.publish("user:login", { id: 1 }); // handler runs
unsub();
bus.publish("user:login", { id: 2 }); // handler does NOT run

Clarifying questions expected:

  • How does this genuinely differ from a plain EventEmitter — is topic-based routing the key distinction?
  • Should publishing to a topic with zero subscribers throw, or be a silent no-op?
  • Do handlers need to run in subscription order, or is order unspecified?

Code / implementation expected: Yes — real, direct proof of multiple subscribers per topic, correct unsubscribe behavior, real topic isolation, and a genuine no-op on a topic with no subscribers.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: multiple subscribers, correct unsubscribe, topic isolation, and a genuine no-op on an unsubscribed topic — verified directly

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 2 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Move Zeroes to End

Continue