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);
});
}
};
}
```