fork download
  1.  
  2. /*
  3. FOLLOW-UP 3: HTTP METHOD PER ROUTE
  4.  
  5. Rules:
  6. 1. Match HTTP method exactly.
  7. 2. Literal segments must match exactly.
  8. 3. {param} matches exactly one non-empty segment.
  9. 4. Route and URL must have equal segment counts.
  10. 5. First registered matching route wins.
  11. 6. Return [method, route, paramName, paramValue, ...].
  12. 7. Return null when no route matches.
  13. */
  14.  
  15. class TrieNode {
  16. constructor() {
  17. this.children = new Map();
  18. this.wild = null;
  19. this.routeIndex = -1;
  20. }
  21. }
  22.  
  23. function matchRoutes(routes, requests) {
  24.  
  25. // NEW: one root per HTTP method
  26. const roots = new Map();
  27.  
  28. // routes[i] = [method, pattern]
  29. const patterns = routes.map(route =>
  30. route[1].slice(1).split("/")
  31. );
  32.  
  33. // ==================================
  34. // STEP 1: BUILD TRIES
  35. // ==================================
  36.  
  37. for (let i = 0; i < routes.length; i++) {
  38.  
  39. const [method, route] = routes[i];
  40.  
  41. // Create root for this method if needed.
  42. if (!roots.has(method)) {
  43. roots.set(method, new TrieNode());
  44. }
  45.  
  46. // Start insertion in this method's Trie.
  47. let node = roots.get(method);
  48.  
  49. for (const part of patterns[i]) {
  50.  
  51. if (part[0] === "{") {
  52.  
  53. if (node.wild === null) {
  54. node.wild = new TrieNode();
  55. }
  56.  
  57. node = node.wild;
  58.  
  59. } else {
  60.  
  61. if (!node.children.has(part)) {
  62. node.children.set(
  63. part,
  64. new TrieNode()
  65. );
  66. }
  67.  
  68. node = node.children.get(part);
  69. }
  70. }
  71.  
  72. // Keep earliest registered matching route.
  73. if (node.routeIndex === -1) {
  74. node.routeIndex = i;
  75. }
  76. }
  77.  
  78. // ==================================
  79. // STEP 2: MATCH REQUESTS
  80. // ==================================
  81.  
  82. const answer = [];
  83.  
  84. for (const [method, url] of requests) {
  85.  
  86. // NEW: get only this method's Trie.
  87. const root = roots.get(method);
  88.  
  89. // No routes registered for this method.
  90. if (root === undefined) {
  91. answer.push(null);
  92. continue;
  93. }
  94.  
  95. const values = url.slice(1).split("/");
  96.  
  97. // [TrieNode, next URL segment index]
  98. const stack = [[root, 0]];
  99.  
  100. // Same sentinel as original solution.
  101. let best = routes.length;
  102.  
  103. while (stack.length > 0) {
  104.  
  105. const [node, pos] = stack.pop();
  106.  
  107. // All URL segments consumed.
  108. if (pos === values.length) {
  109.  
  110. if (node.routeIndex !== -1) {
  111. best = Math.min(
  112. best,
  113. node.routeIndex
  114. );
  115. }
  116.  
  117. continue;
  118. }
  119.  
  120. const segment = values[pos];
  121.  
  122. // OPTION 1: Literal child
  123. const literalChild =
  124. node.children.get(segment);
  125.  
  126. if (literalChild !== undefined) {
  127. stack.push([
  128. literalChild,
  129. pos + 1
  130. ]);
  131. }
  132.  
  133. // OPTION 2: Parameter child
  134. if (
  135. node.wild !== null &&
  136. segment.length > 0
  137. ) {
  138. stack.push([
  139. node.wild,
  140. pos + 1
  141. ]);
  142. }
  143. }
  144.  
  145. // ==================================
  146. // STEP 3: BUILD RESULT
  147. // ==================================
  148.  
  149. if (best === routes.length) {
  150. answer.push(null);
  151. continue;
  152. }
  153.  
  154. const row = [
  155. routes[best][0], // HTTP method
  156. routes[best][1] // Original route pattern
  157. ];
  158.  
  159. const parts = patterns[best];
  160.  
  161. for (let j = 0; j < parts.length; j++) {
  162.  
  163. if (parts[j][0] === "{") {
  164. row.push(
  165. parts[j].slice(1, -1),
  166. values[j]
  167. );
  168. }
  169. }
  170.  
  171. answer.push(row);
  172. }
  173.  
  174. return answer;
  175. }
  176.  
  177.  
  178. // ==================================
  179. // IDEONE TEST HARNESS
  180. // ==================================
  181.  
  182. function runTest(name, routes, requests, expected) {
  183.  
  184. const actual = matchRoutes(routes, requests);
  185.  
  186. const passed =
  187. JSON.stringify(actual) ===
  188. JSON.stringify(expected);
  189.  
  190. console.log(
  191. (passed ? "PASS" : "FAIL") + " - " + name
  192. );
  193.  
  194. if (!passed) {
  195. console.log("Expected:", JSON.stringify(expected));
  196. console.log("Actual: ", JSON.stringify(actual));
  197. }
  198. }
  199.  
  200.  
  201. // 1. Same URL, different methods - imp.
  202. runTest(
  203. "Different HTTP methods",
  204. [
  205. ["GET", "/users/{id}"],
  206. ["POST", "/users/{id}"],
  207. ["DELETE", "/users/{id}"]
  208. ],
  209. [
  210. ["GET", "/users/42"],
  211. ["POST", "/users/42"],
  212. ["DELETE", "/users/42"]
  213. ],
  214. [
  215. ["GET", "/users/{id}", "id", "42"],
  216. ["POST", "/users/{id}", "id", "42"],
  217. ["DELETE", "/users/{id}", "id", "42"]
  218. ]
  219. );
  220.  
  221.  
  222. // 2. Unregistered HTTP method - imp.
  223. runTest(
  224. "Method not registered",
  225. [
  226. ["GET", "/users/{id}"]
  227. ],
  228. [
  229. ["POST", "/users/42"]
  230. ],
  231. [null]
  232. );
  233.  
  234.  
  235. // 3. First registered wins within method - imp.
  236. runTest(
  237. "Registration order",
  238. [
  239. ["GET", "/users/{id}"],
  240. ["GET", "/users/admin"]
  241. ],
  242. [
  243. ["GET", "/users/admin"]
  244. ],
  245. [
  246. ["GET", "/users/{id}", "id", "admin"]
  247. ]
  248. );
  249.  
  250.  
  251. // 4. Other method does not interfere - imp.
  252. runTest(
  253. "Independent method Tries",
  254. [
  255. ["POST", "/users/admin"],
  256. ["GET", "/users/{id}"]
  257. ],
  258. [
  259. ["GET", "/users/admin"]
  260. ],
  261. [
  262. ["GET", "/users/{id}", "id", "admin"]
  263. ]
  264. );
  265.  
  266.  
  267. // 5. Multiple parameters
  268. runTest(
  269. "Multiple parameters",
  270. [
  271. ["GET", "/users/{id}/orders/{orderId}"]
  272. ],
  273. [
  274. ["GET", "/users/42/orders/99"]
  275. ],
  276. [
  277. [
  278. "GET",
  279. "/users/{id}/orders/{orderId}",
  280. "id", "42",
  281. "orderId", "99"
  282. ]
  283. ]
  284. );
  285.  
  286.  
  287. // 6. Literal branch fails, wildcard succeeds
  288. runTest(
  289. "Explore both branches",
  290. [
  291. ["GET", "/users/admin/settings"],
  292. ["GET", "/users/{id}/profile"]
  293. ],
  294. [
  295. ["GET", "/users/admin/profile"]
  296. ],
  297. [
  298. [
  299. "GET",
  300. "/users/{id}/profile",
  301. "id", "admin"
  302. ]
  303. ]
  304. );
  305.  
  306.  
  307. // 7. Empty parameter
  308. runTest(
  309. "Empty parameter rejected",
  310. [
  311. ["GET", "/users/{id}"]
  312. ],
  313. [
  314. ["GET", "/users/"]
  315. ],
  316. [null]
  317. );
  318.  
  319.  
  320. // 8. No matching path
  321. runTest(
  322. "No matching path",
  323. [
  324. ["GET", "/users/{id}"]
  325. ],
  326. [
  327. ["GET", "/products/42"]
  328. ],
  329. [null]
  330. );
  331.  
  332.  
  333. // 9. Duplicate route within same method
  334. runTest(
  335. "Duplicate route",
  336. [
  337. ["GET", "/users/{id}"],
  338. ["GET", "/users/{name}"]
  339. ],
  340. [
  341. ["GET", "/users/42"]
  342. ],
  343. [
  344. ["GET", "/users/{id}", "id", "42"]
  345. ]
  346. );
  347.  
  348.  
  349. // 10. Empty route list
  350. runTest(
  351. "Empty routes",
  352. [],
  353. [
  354. ["GET", "/users/42"]
  355. ],
  356. [null]
  357. );
  358.  
Success #stdin #stdout 0.03s 5600KB
stdin
Standard input is empty
stdout
PASS - Different HTTP methods
PASS - Method not registered
PASS - Registration order
PASS - Independent method Tries
PASS - Multiple parameters
PASS - Explore both branches
PASS - Empty parameter rejected
PASS - No matching path
PASS - Duplicate route
PASS - Empty routes