Explorer
Node.js

Implement a pub/sub system where subscribers can use "*" as a wildcard. `subscribe("user.*", fn)` matches `publish("user.created")`, `publish("user.deleted")`, etc.

Problem Statement

Implement a pub/sub system where subscribers can use "*" as a wildcard. `subscribe("user.*", fn)` matches `publish("user.created")`, `publish("user.deleted")`, etc.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: Store subscribers with their patterns. On publish, match the topic against patterns. šŸ’” Hint 2: Replace "*" in the pattern with a regex wildcard. šŸ’” Hint 3: Convert pattern to regex: pattern.replace("*", ".*") and test against the topic. āœ… Solution: ```javascript function createPubSub() { const subs = []; return { subscribe(pattern, fn) { subs.push({ pattern, fn }); return () => { const i = subs.findIndex(s => s.fn === fn); if (i >= 0) subs.splice(i, 1); }; }, publish(topic, data) { subs.forEach(({ pattern, fn }) => { const regex = new RegExp("^" + pattern.replace(/\*/g, ".*") + "$"); if (regex.test(topic)) fn(data); }); } }; } ```

Pub/Sub with Wildcard Topics

Hard
Implement a pub/sub system where subscribers can use "*" as a wildcard. `subscribe("user.*", fn)` matches `publish("user.created")`, `publish("user.deleted")`, etc.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
["wildcard:alice","exact:alice","wildcard:bob"]