fork download
  1.  
  2. /*
  3. ROUTE PATTERN MATCHER - TRIE + DFS
  4.  
  5. Rules:
  6. 1. Literal segments must match exactly.
  7. 2. {param} matches exactly one non-empty URL segment.
  8. 3. Route and URL must have the same number of segments.
  9. 4. If multiple routes match, return the FIRST registered route.
  10. 5. Return [route, paramName, paramValue, ...].
  11. 6. Return [] if no route matches.
  12. */
  13.  
  14. class TrieNode {
  15. constructor() {
  16. // Map: literal segment -> child TrieNode
  17. this.children = new Map();
  18.  
  19. // Wildcard child for {id}, {name}, etc.
  20. this.wild = null;
  21.  
  22. // Index of first registered route ending here
  23. this.routeIndex = -1;
  24. }
  25. }
  26. function matchRoutes(routes, urls) {
  27.  
  28. // Initially, the Trie contains only the root.
  29. const root = new TrieNode();
  30.  
  31. // Example:
  32. // "/users/admin" -> ["users", "admin"]
  33. // "/users/{id}" -> ["users", "{id}"]
  34. const patterns = routes.map(route =>
  35. route.slice(1).split("/")
  36. );
  37.  
  38. // STEP 1: BUILD TRIE
  39. for (let i = 0; i < routes.length; i++) {
  40. // Every new route starts from root.
  41. let node = root;
  42.  
  43. for (const part of patterns[i]) {
  44.  
  45. /*
  46.   Example: route = "/users/admin"
  47.   parts = ["users", "admin"]
  48.  
  49.   ITERATION 1:
  50.   part = "users"
  51.   node = root
  52.  
  53.   We create/find "users" in root.children.
  54.   Then node becomes NodeUsers.
  55.  
  56.   ITERATION 2:
  57.   part = "admin"
  58.   node = NodeUsers
  59.  
  60.   We create/find "admin" in
  61.   NodeUsers.children.
  62.   Then node becomes NodeAdmin.
  63.  
  64.   The key point:
  65.   'part' is the segment we want to match.
  66.   'node' is the CURRENT TrieNode.
  67.   After processing 'part', we move to
  68.   the child representing that segment.
  69.   */
  70.  
  71. if (part[0] === "{") {
  72.  
  73. // Example route: "/users/{id}"
  74. //
  75. // Iteration 1:
  76. // part = "users", node = root
  77. // Move to NodeUsers.
  78. //
  79. // Iteration 2:
  80. // part = "{id}", node = NodeUsers
  81. // Create/follow NodeUsers.wild.
  82.  
  83. if (node.wild === null) {
  84. // 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.
  85. node.wild = new TrieNode();
  86. }
  87.  
  88. // Move from CURRENT node to wildcard child.
  89. node = node.wild;
  90.  
  91. } else {
  92.  
  93. // Example:
  94. // part = "users", node = root
  95. // root.children.set("users", NodeUsers)
  96. //
  97. // Next iteration:
  98. // part = "admin", node = NodeUsers
  99. // NodeUsers.children.set("admin", NodeAdmin)
  100.  
  101. if (!node.children.has(part)) {
  102. node.children.set(part, new TrieNode());
  103. }
  104.  
  105. // Move to the child we just found/created.
  106. // This changes the local 'node' reference,
  107. // not the structure of the Trie.
  108. node = node.children.get(part);
  109. }
  110. }
  111.  
  112. // We have processed every segment of this route.
  113. // 'node' now points to the FINAL TrieNode.
  114. //
  115. // Example: "/users/admin"
  116. // node = NodeAdmin
  117. //
  118. // Mark this node with the route's index.
  119. if (node.routeIndex === -1) {
  120. node.routeIndex = i;
  121. }
  122. }
  123.  
  124. // =====================================
  125. // STEP 2: MATCH URLs USING DFS
  126. // =====================================
  127.  
  128. const answer = [];
  129.  
  130. for (const url of urls) {
  131.  
  132. // Example:
  133. // url = "/users/admin"
  134. // values = ["users", "admin"]
  135. const values = url.slice(1).split("/");
  136.  
  137. // Each entry: [current TrieNode, next URL index]
  138. const stack = [[root, 0]];
  139.  
  140. // No matching route found yet.
  141. let best = routes.length;
  142. // Why DFS?
  143. // 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
  144.  
  145. while (stack.length > 0) {
  146.  
  147. const [node, pos] = stack.pop();
  148.  
  149. /*
  150.   Example: URL = "/users/admin"
  151.  
  152.   First:
  153.   node = root
  154.   pos = 0
  155.   values[pos] = "users"
  156.  
  157.   After following literal "users":
  158.   node = NodeUsers
  159.   pos = 1
  160.   values[pos] = "admin"
  161.  
  162.   After following literal "admin":
  163.   node = NodeAdmin
  164.   pos = 2
  165.  
  166.   pos = 2 means all URL segments
  167.   have been matched.
  168.   */
  169.  
  170. if (pos === values.length) {
  171.  
  172. // Valid only if a registered route
  173. // ends at this TrieNode.
  174. if (node.routeIndex !== -1) {
  175. best = Math.min(
  176. best,
  177. node.routeIndex
  178. );
  179. }
  180.  
  181. continue;
  182. }
  183.  
  184. // Current URL segment to match.
  185. const segment = values[pos];
  186.  
  187. // OPTION 1: Literal child
  188. //
  189. // Example:
  190. // node = NodeUsers
  191. // segment = "admin"
  192. //
  193. // NodeUsers.children.get("admin")
  194. // returns NodeAdmin if it exists.
  195. const literalChild =
  196. node.children.get(segment);
  197.  
  198. if (literalChild !== undefined) {
  199. stack.push([
  200. literalChild,
  201. pos + 1
  202. ]);
  203. }
  204.  
  205. // OPTION 2: Wildcard child
  206. //
  207. // Example:
  208. // node = NodeUsers
  209. // segment = "admin"
  210. //
  211. // If "/users/{id}" was registered,
  212. // NodeUsers.wild also exists.
  213. //
  214. // Both literal and wildcard children
  215. // can match "admin".
  216. // 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,
  217. // 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
  218. // /users → values = ["users"]. At NodeUsers, pos === values.length, so we finish that path without checking the wildcard.
  219. // /users/ → values = ["users", ""]. At NodeUsers, pos !== values.length, so we do check the wildcard, but reject it because the segment is empty.
  220. if (
  221. node.wild !== null &&
  222. segment.length > 0
  223. ) {
  224. stack.push([
  225. node.wild,
  226. pos + 1
  227. ]);
  228. }
  229.  
  230. // DFS explores both matching branches.
  231. // Registration order, not specificity,
  232. // determines the winning route.
  233.  
  234. // Note above: We use two separate if statements instead of if...else because
  235. // BOTH the literal child and the wildcard child can match the same URL segment.
  236. }
  237.  
  238. // =====================================
  239. // STEP 3: BUILD RESULT
  240. // =====================================
  241.  
  242. const row = [];
  243.  
  244. if (best < routes.length) {
  245.  
  246. row.push(routes[best]);
  247.  
  248. // 'parts' is a reference to the stored
  249. // segments of the winning route.
  250. // This assignment is O(1) space.
  251. const parts = patterns[best];
  252.  
  253. for (let j = 0; j < parts.length; j++) {
  254.  
  255. if (parts[j][0] === "{") {
  256.  
  257. // "{id}" -> "id"
  258. const paramName =
  259. parts[j].slice(1, -1);
  260.  
  261. row.push(paramName, values[j]);
  262. }
  263. }
  264. }
  265.  
  266. answer.push(row);
  267. }
  268.  
  269. return answer;
  270. }
  271.  
  272. // =============================================
  273. // TEST HARNESS - IDEONE READY
  274. // =============================================
  275.  
  276. function runTest(name, routes, urls, expected) {
  277. const actual = matchRoutes(routes, urls);
  278.  
  279. const passed =
  280. JSON.stringify(actual) ===
  281. JSON.stringify(expected);
  282.  
  283. console.log(
  284. (passed ? "PASS" : "FAIL") + " - " + name
  285. );
  286.  
  287. if (!passed) {
  288. console.log(
  289. "Expected:",
  290. JSON.stringify(expected)
  291. );
  292. console.log(
  293. "Actual: ",
  294. JSON.stringify(actual)
  295. );
  296. }
  297. }
  298.  
  299.  
  300. // Test 1: Basic matching - imp.
  301. runTest(
  302. "Basic matching",
  303. [
  304. "/users/{id}/pictures/{pictureId}",
  305. "/health"
  306. ],
  307. [
  308. "/users/101/pictures/1",
  309. "/health",
  310. "/users/101"
  311. ],
  312. [
  313. [
  314. "/users/{id}/pictures/{pictureId}",
  315. "id", "101",
  316. "pictureId", "1"
  317. ],
  318. ["/health"],
  319. []
  320. ]
  321. );
  322.  
  323.  
  324. // Test 2: Wildcard registered first - imp.
  325. runTest(
  326. "Wildcard registered first",
  327. [
  328. "/users/{id}",
  329. "/users/admin"
  330. ],
  331. ["/users/admin"],
  332. [
  333. ["/users/{id}", "id", "admin"]
  334. ]
  335. );
  336.  
  337.  
  338. // Test 3: Literal registered first - imp.
  339. runTest(
  340. "Literal registered first",
  341. [
  342. "/users/admin",
  343. "/users/{id}"
  344. ],
  345. ["/users/admin"],
  346. [
  347. ["/users/admin"]
  348. ]
  349. );
  350.  
  351.  
  352. // Test 4: Multiple parameters - imp.
  353. runTest(
  354. "Multiple parameters",
  355. ["/{type}/{id}"],
  356. ["/orders/7"],
  357. [
  358. [
  359. "/{type}/{id}",
  360. "type", "orders",
  361. "id", "7"
  362. ]
  363. ]
  364. );
  365.  
  366.  
  367. // Test 5: Same wildcard structure
  368. runTest(
  369. "Same wildcard structure",
  370. [
  371. "/users/{id}",
  372. "/users/{name}"
  373. ],
  374. ["/users/42"],
  375. [
  376. ["/users/{id}", "id", "42"]
  377. ]
  378. );
  379.  
  380.  
  381. // Test 6: Different segment counts
  382. runTest(
  383. "Different segment counts",
  384. ["/users/{id}"],
  385. ["/users/42/photos"],
  386. [[]]
  387. );
  388.  
  389.  
  390. // Test 7: No match
  391. runTest(
  392. "No match",
  393. ["/health"],
  394. ["/products"],
  395. [[]]
  396. );
  397.  
  398.  
  399. // Test 8: Case sensitivity
  400. runTest(
  401. "Case sensitivity",
  402. ["/Users/{id}"],
  403. ["/users/42"],
  404. [[]]
  405. );
  406.  
  407.  
  408. // Test 9: Competing DFS paths - imp.
  409. runTest(
  410. "Competing DFS paths",
  411. [
  412. "/{type}/admin",
  413. "/users/{id}",
  414. "/users/admin"
  415. ],
  416. ["/users/admin"],
  417. [
  418. [
  419. "/{type}/admin",
  420. "type", "users"
  421. ]
  422. ]
  423. );
  424.  
  425.  
  426. // Test 10: Wildcard cannot match empty segment
  427. runTest(
  428. "Empty wildcard segment",
  429. ["/users/{id}"],
  430. ["/users/"],
  431. [[]]
  432. );
  433.  
  434.  
  435. // Test 11: Duplicate routes
  436. runTest(
  437. "Duplicate routes",
  438. [
  439. "/users/{id}",
  440. "/users/{id}"
  441. ],
  442. ["/users/5"],
  443. [
  444. ["/users/{id}", "id", "5"]
  445. ]
  446. );
  447.  
Success #stdin #stdout 0.03s 5636KB
stdin
Standard input is empty
stdout
PASS - Basic matching
PASS - Wildcard registered first
PASS - Literal registered first
PASS - Multiple parameters
PASS - Same wildcard structure
PASS - Different segment counts
PASS - No match
PASS - Case sensitivity
PASS - Competing DFS paths
PASS - Empty wildcard segment
PASS - Duplicate routes