fork download
  1.  
  2. /*
  3. Route Pattern Matcher
  4. Approach: Brute Force
  5.  
  6. R = number of registered routes
  7. U = number of incoming URLs
  8. L = maximum number of path segments
  9.  
  10. TIME COMPLEXITY: O(U * R * L)
  11. - Preprocessing routes: O(R * L)
  12. - For each of U URLs, check up to R routes.
  13. - Each route comparison takes up to O(L).
  14. - Total: O(R * L + U * R * L)
  15.   = O(U * R * L)
  16.  
  17. SPACE COMPLEXITY:
  18. - Auxiliary Space: O(R * L)
  19. - Including output: O((R + U) * L)
  20.  
  21. Breakdown:
  22. 1. patterns: O(R * L)
  23.   Stores the split segments of all R routes.
  24.  
  25. 2. values: O(L)
  26.   Stores segments of the current URL.
  27.  
  28. 3. parts: O(1)
  29.   const parts = patterns[i];
  30.   This creates a REFERENCE to an existing array,
  31.   NOT a new array. No O(L) copy is made.
  32.  
  33.   In contrast:
  34.   const parts = [...patterns[i]];
  35.   This creates a NEW array and takes O(L) space.
  36.  
  37. 4. row: O(L)
  38.   Stores the matching route and extracted parameters.
  39.  
  40. 5. isMatch, i, j: O(1)
  41.  
  42. 6. answer: O(U * L)
  43.   Stores results for all URLs (output space).
  44.  
  45. Auxiliary Space:
  46. O(R * L + L + L + 1) = O(R * L)
  47.  
  48. Note: Complexity uses segment-level analysis,
  49. assuming constant-time segment comparisons.
  50. */
  51.  
  52.  
  53. function matchRoutes(routes, urls) {
  54.  
  55. // Split all registered routes into segments.
  56. // TC: O(R * L), SC: O(R * L)
  57. const patterns = routes.map(route =>
  58. route.slice(1).split("/")
  59. );
  60.  
  61. // Stores final output.
  62. // SC: O(U * L), counted as output space.
  63. const answer = [];
  64.  
  65. // Process each URL.
  66. // U iterations
  67. for (const url of urls) {
  68.  
  69. // Split current URL into segments.
  70. // TC: O(L), SC: O(L)
  71. const values = url.slice(1).split("/");
  72.  
  73. // Empty result if no route matches.
  74. // SC: O(L) maximum when populated.
  75. let row = [];
  76.  
  77. // Check registered routes in original order.
  78. // Up to R routes per URL.
  79. for (let i = 0; i < patterns.length; i++) {
  80.  
  81. // SC: O(1)
  82. // parts references patterns[i].
  83. // It does NOT create a new array.
  84. const parts = patterns[i];
  85.  
  86. // Routes with different segment counts
  87. // cannot match.
  88. if (parts.length !== values.length) {
  89. continue;
  90. }
  91.  
  92. let isMatch = true; // SC: O(1)
  93.  
  94. // Compare up to L segments.
  95. // TC: O(L) per route.
  96. for (let j = 0; j < parts.length; j++) {
  97.  
  98. const part = parts[j];
  99. const value = values[j];
  100.  
  101. // Parameter: {name} matches any segment.
  102. // Literal: must match exactly.
  103. if (!part.startsWith("{") && part !== value) {
  104. isMatch = false;
  105. break;
  106. }
  107. }
  108.  
  109. // Try the next registered route.
  110. if (!isMatch) {
  111. continue;
  112. }
  113.  
  114. // Matching route found.
  115. row = [routes[i]];
  116.  
  117. // Extract parameter names and values.
  118. // TC: O(L), row space: O(L)
  119. for (let j = 0; j < parts.length; j++) {
  120.  
  121. if (parts[j].startsWith("{")) {
  122.  
  123. // Remove opening and closing braces.
  124. const name = parts[j].slice(1, -1);
  125.  
  126. // Add parameter name and URL value.
  127. row.push(name, values[j]);
  128. }
  129. }
  130.  
  131. // First registered matching route wins.
  132. break;
  133. }
  134.  
  135. // Add matched row or [].
  136. answer.push(row);
  137. }
  138.  
  139. return answer;
  140. }
  141.  
  142.  
  143. // ---------------- TEST HARNESS ----------------
  144.  
  145. function runTest(name, routes, urls, expected) {
  146. const actual = matchRoutes(routes, urls);
  147.  
  148. const passed =
  149. JSON.stringify(actual) === JSON.stringify(expected);
  150.  
  151. console.log((passed ? "PASS" : "FAIL") + " - " + name);
  152.  
  153. if (!passed) {
  154. console.log("Expected:", JSON.stringify(expected));
  155. console.log("Actual: ", JSON.stringify(actual));
  156. }
  157. }
  158.  
  159.  
  160. // 1. Basic matching - imp.
  161. runTest(
  162. "Basic matching",
  163. ["/users/{id}/pictures/{pictureId}", "/health"],
  164. ["/users/101/pictures/1", "/health", "/users/1"],
  165. [
  166. ["/users/{id}/pictures/{pictureId}",
  167. "id", "101", "pictureId", "1"],
  168. ["/health"],
  169. []
  170. ]
  171. );
  172.  
  173.  
  174. // 2. First registered match wins - imp.
  175. runTest(
  176. "Registration precedence",
  177. ["/users/{id}", "/users/admin"],
  178. ["/users/admin"],
  179. [
  180. ["/users/{id}", "id", "admin"]
  181. ]
  182. );
  183.  
  184.  
  185. // 3. Multiple parameters - imp.
  186. runTest(
  187. "Multiple parameters",
  188. ["/{type}/{id}"],
  189. ["/orders/7"],
  190. [
  191. ["/{type}/{id}", "type", "orders", "id", "7"]
  192. ]
  193. );
  194.  
  195.  
  196. // 4. Different segment counts
  197. runTest(
  198. "Different segment counts",
  199. ["/users/{id}"],
  200. ["/users/1/photos"],
  201. [[]]
  202. );
  203.  
  204.  
  205. // 5. Case-sensitive matching
  206. runTest(
  207. "Case sensitivity",
  208. ["/Users/{id}"],
  209. ["/users/1"],
  210. [[]]
  211. );
  212.  
  213.  
  214. // 6. No matching route - imp.
  215. runTest(
  216. "No matching route",
  217. ["/health", "/users/{id}"],
  218. ["/products/10"],
  219. [[]]
  220. );
  221.  
  222.  
  223. // 7. Literal route registered first
  224. runTest(
  225. "Literal precedence",
  226. ["/users/admin", "/users/{id}"],
  227. ["/users/admin"],
  228. [["/users/admin"]]
  229. );
  230.  
  231.  
  232. // 8. Routes sharing prefixes
  233. runTest(
  234. "Shared prefixes",
  235. ["/users/{id}", "/users/{id}/posts/{postId}"],
  236. ["/users/5", "/users/5/posts/10"],
  237. [
  238. ["/users/{id}", "id", "5"],
  239. ["/users/{id}/posts/{postId}",
  240. "id", "5", "postId", "10"]
  241. ]
  242. );
  243.  
Success #stdin #stdout 0.03s 5692KB
stdin
Standard input is empty
stdout
PASS - Basic matching
PASS - Registration precedence
PASS - Multiple parameters
PASS - Different segment counts
PASS - Case sensitivity
PASS - No matching route
PASS - Literal precedence
PASS - Shared prefixes