/*
ROUTE PATTERN MATCHER - TRIE + DFS
Rules:
1. Literal segments must match exactly.
2. {param} matches exactly one non-empty URL segment.
3. Route and URL must have the same number of segments.
4. If multiple routes match, return the FIRST registered route.
5. Return [route, paramName, paramValue, ...].
6. Return [] if no route matches.
*/
class TrieNode {
constructor() {
// Map: literal segment -> child TrieNode
this.children = new Map();
// Wildcard child for {id}, {name}, etc.
this.wild = null;
// Index of first registered route ending here
this.routeIndex = -1;
}
}
function matchRoutes(routes, urls) {
// Initially, the Trie contains only the root.
const root = new TrieNode();
// Example:
// "/users/admin" -> ["users", "admin"]
// "/users/{id}" -> ["users", "{id}"]
const patterns = routes.map(route =>
route.slice(1).split("/")
);
// STEP 1: BUILD TRIE
for (let i = 0; i < routes.length; i++) {
// Every new route starts from root.
let node = root;
for (const part of patterns[i]) {
/*
Example: route = "/users/admin"
parts = ["users", "admin"]
ITERATION 1:
part = "users"
node = root
We create/find "users" in root.children.
Then node becomes NodeUsers.
ITERATION 2:
part = "admin"
node = NodeUsers
We create/find "admin" in
NodeUsers.children.
Then node becomes NodeAdmin.
The key point:
'part' is the segment we want to match.
'node' is the CURRENT TrieNode.
After processing 'part', we move to
the child representing that segment.
*/
if (part[0] === "{") {
// Example route: "/users/{id}"
//
// Iteration 1:
// part = "users", node = root
// Move to NodeUsers.
//
// Iteration 2:
// part = "{id}", node = NodeUsers
// Create/follow NodeUsers.wild.
if (node.wild === null) {
// here we don't the wildcard value so we are not storing it in the children map and have it as a different trienode value which can be anything.
node.wild = new TrieNode();
}
// Move from CURRENT node to wildcard child.
node = node.wild;
} else {
// Example:
// part = "users", node = root
// root.children.set("users", NodeUsers)
//
// Next iteration:
// part = "admin", node = NodeUsers
// NodeUsers.children.set("admin", NodeAdmin)
if (!node.children.has(part)) {
node.children.set(part, new TrieNode());
}
// Move to the child we just found/created.
// This changes the local 'node' reference,
// not the structure of the Trie.
node = node.children.get(part);
}
}
// We have processed every segment of this route.
// 'node' now points to the FINAL TrieNode.
//
// Example: "/users/admin"
// node = NodeAdmin
//
// Mark this node with the route's index.
if (node.routeIndex === -1) {
node.routeIndex = i;
}
}
// =====================================
// STEP 2: MATCH URLs USING DFS
// =====================================
const answer = [];
for (const url of urls) {
// Example:
// url = "/users/admin"
// values = ["users", "admin"]
const values = url.slice(1).split("/");
// Each entry: [current TrieNode, next URL index]
const stack = [[root, 0]];
// No matching route found yet.
let best = routes.length;
// Why DFS?
// one url can match different routes that the thing in this question - so we push or explore all the paths to find the matching url, and even if all the routes match the given URL, we alwasy return the one that appear first in the route list order
while (stack.length > 0) {
const [node, pos] = stack.pop();
/*
Example: URL = "/users/admin"
First:
node = root
pos = 0
values[pos] = "users"
After following literal "users":
node = NodeUsers
pos = 1
values[pos] = "admin"
After following literal "admin":
node = NodeAdmin
pos = 2
pos = 2 means all URL segments
have been matched.
*/
if (pos === values.length) {
// Valid only if a registered route
// ends at this TrieNode.
if (node.routeIndex !== -1) {
best = Math.min(
best,
node.routeIndex
);
}
continue;
}
// Current URL segment to match.
const segment = values[pos];
// OPTION 1: Literal child
//
// Example:
// node = NodeUsers
// segment = "admin"
//
// NodeUsers.children.get("admin")
// returns NodeAdmin if it exists.
const literalChild =
node.children.get(segment);
if (literalChild !== undefined) {
stack.push([
literalChild,
pos + 1
]);
}
// OPTION 2: Wildcard child
//
// Example:
// node = NodeUsers
// segment = "admin"
//
// If "/users/{id}" was registered,
// NodeUsers.wild also exists.
//
// Both literal and wildcard children
// can match "admin".
// so if we ahve registered that node.wild != null, then for this if condn to be true and push this TRie node value into the stack,
// we need segment.length > 0. B/c there has to be segement before the wildcard value in the given URL to match. So it cannot be like '101', or /users/, or /user
// /users → values = ["users"]. At NodeUsers, pos === values.length, so we finish that path without checking the wildcard.
// /users/ → values = ["users", ""]. At NodeUsers, pos !== values.length, so we do check the wildcard, but reject it because the segment is empty.
if (
node.wild !== null &&
segment.length > 0
) {
stack.push([
node.wild,
pos + 1
]);
}
// DFS explores both matching branches.
// Registration order, not specificity,
// determines the winning route.
// Note above: We use two separate if statements instead of if...else because
// BOTH the literal child and the wildcard child can match the same URL segment.
}
// =====================================
// STEP 3: BUILD RESULT
// =====================================
const row = [];
if (best < routes.length) {
row.push(routes[best]);
// 'parts' is a reference to the stored
// segments of the winning route.
// This assignment is O(1) space.
const parts = patterns[best];
for (let j = 0; j < parts.length; j++) {
if (parts[j][0] === "{") {
// "{id}" -> "id"
const paramName =
parts[j].slice(1, -1);
row.push(paramName, values[j]);
}
}
}
answer.push(row);
}
return answer;
}
// =============================================
// TEST HARNESS - IDEONE READY
// =============================================
function runTest(name, routes, urls, expected) {
const actual = matchRoutes(routes, urls);
const passed =
JSON.stringify(actual) ===
JSON.stringify(expected);
console.log(
(passed ? "PASS" : "FAIL") + " - " + name
);
if (!passed) {
console.log(
"Expected:",
JSON.stringify(expected)
);
console.log(
"Actual: ",
JSON.stringify(actual)
);
}
}
// Test 1: Basic matching - imp.
runTest(
"Basic matching",
[
"/users/{id}/pictures/{pictureId}",
"/health"
],
[
"/users/101/pictures/1",
"/health",
"/users/101"
],
[
[
"/users/{id}/pictures/{pictureId}",
"id", "101",
"pictureId", "1"
],
["/health"],
[]
]
);
// Test 2: Wildcard registered first - imp.
runTest(
"Wildcard registered first",
[
"/users/{id}",
"/users/admin"
],
["/users/admin"],
[
["/users/{id}", "id", "admin"]
]
);
// Test 3: Literal registered first - imp.
runTest(
"Literal registered first",
[
"/users/admin",
"/users/{id}"
],
["/users/admin"],
[
["/users/admin"]
]
);
// Test 4: Multiple parameters - imp.
runTest(
"Multiple parameters",
["/{type}/{id}"],
["/orders/7"],
[
[
"/{type}/{id}",
"type", "orders",
"id", "7"
]
]
);
// Test 5: Same wildcard structure
runTest(
"Same wildcard structure",
[
"/users/{id}",
"/users/{name}"
],
["/users/42"],
[
["/users/{id}", "id", "42"]
]
);
// Test 6: Different segment counts
runTest(
"Different segment counts",
["/users/{id}"],
["/users/42/photos"],
[[]]
);
// Test 7: No match
runTest(
"No match",
["/health"],
["/products"],
[[]]
);
// Test 8: Case sensitivity
runTest(
"Case sensitivity",
["/Users/{id}"],
["/users/42"],
[[]]
);
// Test 9: Competing DFS paths - imp.
runTest(
"Competing DFS paths",
[
"/{type}/admin",
"/users/{id}",
"/users/admin"
],
["/users/admin"],
[
[
"/{type}/admin",
"type", "users"
]
]
);
// Test 10: Wildcard cannot match empty segment
runTest(
"Empty wildcard segment",
["/users/{id}"],
["/users/"],
[[]]
);
// Test 11: Duplicate routes
runTest(
"Duplicate routes",
[
"/users/{id}",
"/users/{id}"
],
["/users/5"],
[
["/users/{id}", "id", "5"]
]
);