Skip to content

Commit

Permalink
refactor(matcher): improve readability
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Jul 8, 2024
1 parent c81d596 commit af7af4d
Showing 1 changed file with 18 additions and 24 deletions.
42 changes: 18 additions & 24 deletions src/operations/match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,42 +18,36 @@ function _matchAll<T>(
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;
}

0 comments on commit af7af4d

Please sign in to comment.