Skip to content

Commit

Permalink
avoid using a regex
Browse files Browse the repository at this point in the history
  • Loading branch information
ghalle committed Dec 21, 2024
1 parent 3355df0 commit cde7062
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ export function pathToPattern(path: string): string {

let route = "";

let nonOptionalSegments = 0;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];

Expand Down Expand Up @@ -217,20 +218,26 @@ export function pathToPattern(path: string): string {
}
}

route += (optional ? "" : "/") + pattern;
if (optional) {
route += pattern;
} else {
nonOptionalSegments++;
route += "/" + pattern;
}
}

// Case: /(group)/index.tsx
if (route === "") {
route = "/";
}

// Handles all cases where an optional parameter is the
// first and only non-group segment
// Handles all cases where a route starts with
// an optional parameter and does not contain
// any non-group and non-optional segments after
// Case: /[[id]].tsx
// Case: /(group)/[[id]].tsx
// Case: /(group)/[[name]]/(group2)/index.tsx
if (route.startsWith(`{/`) && !/(?<!{)\//.test(route)) {
if (route.startsWith(`{/`) && nonOptionalSegments === 0) {
route = route.replace("{/", "/{");
}

Expand Down

0 comments on commit cde7062

Please sign in to comment.