From af7af4d49a037837616ac1008fa47c6c0a73e085 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Mon, 8 Jul 2024 12:22:09 +0200 Subject: [PATCH] refactor(matcher): improve readability --- src/operations/match.ts | 42 ++++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/src/operations/match.ts b/src/operations/match.ts index 93dd334..4fd0b22 100644 --- a/src/operations/match.ts +++ b/src/operations/match.ts @@ -18,42 +18,36 @@ function _matchAll( method: string, segments: string[], index: number, + matches: T[] = [], ): T[] { - const matchedNodes: T[] = []; - const segment = segments[index]; - // 1. Node self data - if (index === segments.length && node.methods) { - const match = node.methods[method] || node.methods[""]; + // Wildcard + if (node.wildcard && node.wildcard.methods) { + const match = node.wildcard.methods[method] || node.wildcard.methods[""]; if (match) { - matchedNodes.unshift(match[0 /* data */]); + matches.push(match[0 /* data */]); } } - // 2. Static - const staticChild = node.static?.[segment]; - if (staticChild) { - matchedNodes.unshift( - ..._matchAll(ctx, staticChild, method, segments, index + 1), - ); - } - - // 3. Param + // Param if (node.param) { - matchedNodes.unshift( - ..._matchAll(ctx, node.param, method, segments, index + 1), - ); + _matchAll(ctx, node.param, method, segments, index + 1, matches); } - // 4. Wildcard - if (node.wildcard && node.wildcard.methods) { - const match = node.wildcard.methods[method] || node.wildcard.methods[""]; + // Node self data (only if we reached the end of the path) + if (index === segments.length && node.methods) { + const match = node.methods[method] || node.methods[""]; if (match) { - matchedNodes.unshift(match[0 /* data */]); + matches.push(match[0 /* data */]); } } - // No match - return matchedNodes; + // Static + const staticChild = node.static?.[segment]; + if (staticChild) { + _matchAll(ctx, staticChild, method, segments, index + 1, matches); + } + + return matches; }