/*
ROUTE PATTERN MATCHER - TRIE + DFS
FOLLOW-UP: LITERAL VS PARAMETER PRECEDENCE
Rules:
1. Literal segments must match exactly.
2. {param} matches one non-empty segment.
3. Route and URL must have equal segment counts.
4. Among matching routes, prefer the route with
MORE literal segments.
5. If literal counts tie, FIRST registered wins.
6. Return [route, paramName, paramValue, ...].
7. Return null if nothing matches.
Example:
routes = [
"/users/{id}", // 1 literal
"/users/admin" // 2 literals
]
url = "/users/admin"
Answer = ["/users/admin"]
*/
class TrieNode {
constructor() {
// Literal segment -> child TrieNode
this.children = new Map();
// Child for {param}
this.wild = null;
// Earliest route ending at this node
this.routeIndex = -1;
}
}
function matchRoutes(routes, urls) {
const root = new TrieNode();
const patterns = routes.map(route =>
route.slice(1).split("/")
);
// Count literal segments for each route.
const literalCounts = patterns.map(parts => {
let count = 0;
for (const part of parts) {
if (part[0] !== "{") {
count++;
}
}
return count;
});
// =====================================
// STEP 1: BUILD TRIE
// =====================================
for (let i = 0; i < routes.length; i++) {
// Every route starts at root.
let node = root;
for (const part of patterns[i]) {
/*
Example: "/users/admin"
Iteration 1:
part = "users"
node = root
Move to NodeUsers.
Iteration 2:
part = "admin"
node = NodeUsers
Move to NodeAdmin.
'part' = current route segment.
'node' = current TrieNode object.
*/
if (part[0] === "{") {
if (node.wild === null) {
node.wild = new TrieNode();
}
node = node.wild;
} else {
if (!node.children.has(part)) {
node.children.set(
part,
new TrieNode()
);
}
node = node.children.get(part);
}
}
// Keep first registered route ending here.
//
// Routes sharing an identical Trie path
// have the same literal/wildcard structure,
// so their literal counts are also equal.
if (node.routeIndex === -1) {
node.routeIndex = i;
}
}
// =====================================
// STEP 2: MATCH URLs USING DFS
// =====================================
const answer = [];
for (const url of urls) {
const values = url.slice(1).split("/");
// [TrieNode, next URL segment position]
const stack = [[root, 0]];
let best = -1;
while (stack.length > 0) {
const [node, pos] = stack.pop();
// All URL segments consumed.
if (pos === values.length) {
if (node.routeIndex !== -1) {
const candidate = node.routeIndex;
// First valid route found.
if (best === -1) {
best = candidate;
}
// NEW: Prefer more literal segments.
else if (
literalCounts[candidate] >
literalCounts[best]
) {
best = candidate;
}
// Same specificity:
// first registered route wins.
else if (
literalCounts[candidate] ===
literalCounts[best] &&
candidate < best
) {
best = candidate;
}
}
continue;
}
const segment = values[pos];
// OPTION 1: Literal child
const literalChild =
node.children.get(segment);
if (literalChild !== undefined) {
stack.push([
literalChild,
pos + 1
]);
}
// OPTION 2: Parameter child
if (
node.wild !== null &&
segment.length > 0
) {
stack.push([
node.wild,
pos + 1
]);
}
/*
WHY TWO IF STATEMENTS?
Example:
routes:
/users/{id}
/users/admin
URL: /users/admin
At NodeUsers:
literalChild = NodeAdmin
node.wild = NodeWild
Both match "admin".
We explore BOTH because a literal
branch might fail at a later segment,
while the wildcard branch succeeds.
We choose the best COMPLETE match,
not just the first matching child.
*/
}
// =====================================
// STEP 3: BUILD RESULT
// =====================================
if (best === -1) {
answer.push(null);
continue;
}
const row = [routes[best]];
// O(1) reference assignment
const parts = patterns[best];
for (let j = 0; j < parts.length; j++) {
if (parts[j][0] === "{") {
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)
);
}
}
// 1. Literal beats earlier parameter - imp.
runTest(
"Literal precedence",
["/users/{id}", "/users/admin"],
["/users/admin"],
[["/users/admin"]]
);
// 2. Parameter still matches other values
runTest(
"Parameter matching",
["/users/{id}", "/users/admin"],
["/users/42"],
[["/users/{id}", "id", "42"]]
);
// 3. Literal branch fails later - imp.
runTest(
"Literal branch fails later",
[
"/users/admin/settings",
"/users/{id}/profile"
],
["/users/admin/profile"],
[
["/users/{id}/profile", "id", "admin"]
]
);
// 4. More literal segments wins - imp.
runTest(
"More literals wins",
[
"/{type}/{id}",
"/users/{id}",
"/users/admin"
],
["/users/admin"],
[["/users/admin"]]
);
// 5. Tie: first registered wins - imp.
runTest(
"Equal specificity",
[
"/{type}/admin",
"/users/{id}"
],
["/users/admin"],
[
["/{type}/admin", "type", "users"]
]
);
// 6. Later route with more literals wins
runTest(
"Later more-specific route",
[
"/{a}/{b}/profile",
"/users/{id}/profile"
],
["/users/42/profile"],
[
["/users/{id}/profile", "id", "42"]
]
);
// 7. Multiple named parameters
runTest(
"Multiple parameters",
["/users/{id}/orders/{orderId}"],
["/users/42/orders/99"],
[
[
"/users/{id}/orders/{orderId}",
"id", "42",
"orderId", "99"
]
]
);
// 8. No match
runTest(
"No match",
["/users/admin"],
["/products/42"],
[null]
);
// 9. Case-sensitive literal matching
runTest(
"Case sensitivity",
["/Users/admin"],
["/users/admin"],
[null]
);
// 10. Empty parameter cannot match
runTest(
"Empty parameter",
["/users/{id}"],
["/users/"],
[null]
);
// 11. Duplicate wildcard structure
runTest(
"Duplicate wildcard structure",
["/users/{id}", "/users/{name}"],
["/users/42"],
[["/users/{id}", "id", "42"]]
);