Skip to content

Commit

Permalink
refactor: use regex instead of for loop to replace path params
Browse files Browse the repository at this point in the history
  • Loading branch information
lukemorales committed Feb 6, 2024
1 parent 2d784cb commit a5194b3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/strong-candles-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"next-safe-navigation": patch
---

Use regex instead of for loop to replace path params
11 changes: 6 additions & 5 deletions src/make-route-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ type RouteBuilderResult<
RouteBuilder<Params, Search>
: never;

const PATH_PARAM_REGEX = /\[([^[\]]+)]/g;

// @ts-expect-error overload signature does match the implementation,
// the compiler complains about EnsurePathWithNoParams, but it is fine
export function makeRouteBuilder<Path extends PathBlueprint>(
Expand Down Expand Up @@ -113,13 +115,12 @@ export function makeRouteBuilder(
}

const routeBuilder: RouteBuilder<any, any> = (options) => {
let basePath: string = path;

const { search = {}, ...params } = options ?? {};

for (const [param, value] of Object.entries(params)) {
basePath = basePath.replace(`[${param}]`, `${value}`);
}
const basePath = path.replace(
PATH_PARAM_REGEX,
(match, param) => params[param] ?? match,
);

const urlSearchParams = convertObjectToURLSearchParams(search);

Expand Down

0 comments on commit a5194b3

Please sign in to comment.