Topic routing with wildcards
Implement createBroker(), the routing of a message broker's topic exchange. It returns an object with subscribe(name, pattern), unsubscribe(name) and publish(topic). Topics and patterns are words joined by dots, such as orders.paid.eu. In a pattern, * matches exactly one word and # matches zero or more words, anywhere in the pattern; any other word must be equal. publish returns the names whose pattern matches the topic, in the order they subscribed. Subscribing a name again replaces its pattern and keeps its place; a name that unsubscribed and comes back goes last. In the tests an op [at, method, ...args] calls that method at virtual time at (ms); the answer lists what each call returned. subscribe and unsubscribe return nothing, so the answer lists only publish.
Start from
function createBroker() {
// Return { subscribe, unsubscribe, publish } with * and # wildcards.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Split both strings on dots and compare word lists, not characters: a dot in a regular expression matches any character.
Hint 2
Match recursively with two positions, one in the pattern and one in the topic. A * or an equal word moves both by one.
Hint 3
For #, try every number of topic words it could take, from zero to all that are left. A Map keeps the subscription order and keeps a key's place when it is set again.
Solution
The app has this lab in JavaScript, TypeScript and Python. This page shows the JavaScript code.
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function createBroker() {
const subscriptions = new Map();
function matches(pattern, words, i = 0, j = 0) {
if (i === pattern.length) return j === words.length;
if (pattern[i] === "#") {
for (let k = j; k <= words.length; k++)
if (matches(pattern, words, i + 1, k)) return true;
return false;
}
if (j === words.length) return false;
return (pattern[i] === "*" || pattern[i] === words[j]) && matches(pattern, words, i + 1, j + 1);
}
return {
subscribe(name, pattern) {
subscriptions.set(name, pattern.split("."));
},
unsubscribe(name) {
subscriptions.delete(name);
},
publish(topic) {
const words = topic.split(".");
return [...subscriptions].filter(([, pattern]) => matches(pattern, words)).map(([name]) => name);
},
};
}What an interviewer looks for
Message brokers such as RabbitMQ route events to services by topic patterns. The lab checks the difference between one word and any number of words, which is where most hand-written matchers go wrong.