Skip to content

Commit

Permalink
perf(utils/url): shorten mergePath and optimize for normal use cases. (
Browse files Browse the repository at this point in the history
  • Loading branch information
usualoma authored Feb 12, 2025
1 parent 8340a7b commit 40ea0ee
Showing 1 changed file with 20 additions and 31 deletions.
51 changes: 20 additions & 31 deletions src/utils/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,38 +136,27 @@ export const getPathNoStrict = (request: Request): string => {
return result.length > 1 && result.at(-1) === '/' ? result.slice(0, -1) : result
}

export const mergePath = (...paths: string[]): string => {
let p: string = ''
let endsWithSlash = false

for (let path of paths) {
// calculate endsWithSlash at the start of each iteration
endsWithSlash = p.at(-1) === '/'

/* ['/hey/','/say'] => ['/hey', '/say'] */
if (endsWithSlash) {
p = p.slice(0, -1)
}

/* ['/hey','say'] => ['/hey', '/say'] */
if (path[0] !== '/') {
path = `/${path}`
}

/* ['/hey/', '/'] => `/hey/` */
if (path === '/' && endsWithSlash) {
p = `${p}/`
} else if (path !== '/') {
p = `${p}${path}`
}

/* ['/', '/'] => `/` */
if (path === '/' && p === '') {
p = '/'
}
/**
* Merge paths.
* @param {string[]} ...paths - The paths to merge.
* @returns {string} The merged path.
* @example
* mergePath('/api', '/users') // '/api/users'
* mergePath('/api/', '/users') // '/api/users'
* mergePath('/api', '/') // '/api'
* mergePath('/api/', '/') // '/api/'
*/
export const mergePath: (...paths: string[]) => string = (
base: string | undefined,
sub: string | undefined,
...rest: string[]
): string => {
if (rest.length) {
sub = mergePath(sub as string, ...rest)
}

return p
return `${base?.[0] === '/' ? '' : '/'}${base}${
sub === '/' ? '' : `${base?.at(-1) === '/' ? '' : '/'}${sub?.[0] === '/' ? sub.slice(1) : sub}`
}`
}

export const checkOptionalParameter = (path: string): string[] | null => {
Expand Down

0 comments on commit 40ea0ee

Please sign in to comment.