Skip to content
Myr

perf(utils/url): shorten mergePath and optimize for normal use cases. (#3911)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Taku Amano · committed by GitHub · parent 8340a7b · Browse files · 1 file+20 added−31 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+20 added−31 removed

  • other:+20 added−31 removed

1 file+20 added−31 removed

modified:src/utils/url.ts+20 added-31 removed
134 unmodified lines
135 // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same136 return result.length > 1 && result.at(-1) === '/' ? result.slice(0, -1) : result137}138139export const mergePath = (...paths: string[]): string => {140 let p: string = ''141 let endsWithSlash = false142143 for (let path of paths) {144 // calculate endsWithSlash at the start of each iteration145 endsWithSlash = p.at(-1) === '/'146147 /* ['/hey/','/say'] => ['/hey', '/say'] */148 if (endsWithSlash) {149 p = p.slice(0, -1)150 }151152 /* ['/hey','say'] => ['/hey', '/say'] */153 if (path[0] !== '/') {154 path = `/${path}`155 }156157 /* ['/hey/', '/'] => `/hey/` */158 if (path === '/' && endsWithSlash) {159 p = `${p}/`160 } else if (path !== '/') {161 p = `${p}${path}`162 }163164 /* ['/', '/'] => `/` */165 if (path === '/' && p === '') {166 p = '/'167 }139/**140 * Merge paths.141 * @param {string[]} ...paths - The paths to merge.142 * @returns {string} The merged path.143 * @example144 * mergePath('/api', '/users') // '/api/users'145 * mergePath('/api/', '/users') // '/api/users'146 * mergePath('/api', '/') // '/api'147 * mergePath('/api/', '/') // '/api/'148 */149export const mergePath: (...paths: string[]) => string = (150 base: string | undefined,151 sub: string | undefined,152 ...rest: string[]153): string => {154 if (rest.length) {155 sub = mergePath(sub as string, ...rest)156 }169170 return p157 return `${base?.[0] === '/' ? '' : '/'}${base}${158 sub === '/' ? '' : `${base?.at(-1) === '/' ? '' : '/'}${sub?.[0] === '/' ? sub.slice(1) : sub}`159 }`160}161162export const checkOptionalParameter = (path: string): string[] | null => {163 /*
144 unmodified lines