Skip to content

Commit

Permalink
perf(shared): reduce regexp match usage (#1315)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mister-Hope committed May 8, 2023
1 parent 3382bb1 commit 23bdec6
Show file tree
Hide file tree
Showing 5 changed files with 13 additions and 8 deletions.
2 changes: 1 addition & 1 deletion packages/shared/src/utils/ensureEndingSlash.ts
Expand Up @@ -2,4 +2,4 @@
* Ensure a url string to have ending slash /
*/
export const ensureEndingSlash = (str: string): string =>
/(\.html|\/)$/.test(str) ? str : str + '/'
str[str.length - 1] === '/' || str.endsWith('.html') ? str : `${str}/`
2 changes: 1 addition & 1 deletion packages/shared/src/utils/ensureLeadingSlash.ts
Expand Up @@ -2,4 +2,4 @@
* Ensure a url string to have leading slash /
*/
export const ensureLeadingSlash = (str: string): string =>
str.replace(/^\/?/, '/')
str[0] === '/' ? str : `/${str}`
3 changes: 2 additions & 1 deletion packages/shared/src/utils/removeEndingSlash.ts
@@ -1,4 +1,5 @@
/**
* Remove ending slash / from a string
*/
export const removeEndingSlash = (str: string): string => str.replace(/\/$/, '')
export const removeEndingSlash = (str: string): string =>
str[str.length - 1] === '/' ? str.slice(0, -1) : str
2 changes: 1 addition & 1 deletion packages/shared/src/utils/removeLeadingSlash.ts
Expand Up @@ -2,4 +2,4 @@
* Remove leading slash / from a string
*/
export const removeLeadingSlash = (str: string): string =>
str.replace(/^\//, '')
str[0] === '/' ? str.slice(1) : str
12 changes: 8 additions & 4 deletions packages/shared/src/utils/resolveRoutePathFromUrl.ts
@@ -1,6 +1,10 @@
export const resolveRoutePathFromUrl = (url: string, base = '/'): string =>
url
export const resolveRoutePathFromUrl = (url: string, base = '/'): string => {
const pathname = url
// remove url origin
.replace(/^(https?:)?\/\/[^/]*/, '')
// remove site base
.replace(new RegExp(`^${base}`), '/')

// remove site base
return pathname.startsWith(base)
? `/${pathname.slice(base.length)}`
: pathname
}

0 comments on commit 23bdec6

Please sign in to comment.