Skip to content
Myr

perf(util): cache regex result for URL path(s) (#284)

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

authored by Yusuke Wada · committed by GitHub · parent 5b561bf · Browse files · 2 files+21 added−5 removed
This commit

State

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

Diff stats

2 files+21 added−5 removed

  • tests:+7 added−0 removed
  • other:+14 added−5 removed

2 files+21 added−5 removed

modified:src/utils/url.test.ts+7 added
modified:src/utils/url.ts+14 added-5 removed
1const URL_REGEXP = /^https?:\/\/[a-zA-Z0-9\-\.:]+(\/?[^?#]*)/23export type Pattern = readonly [string, string, RegExp | true] | '*'45const splitPathCache: Record<string, string[]> = {}6export const splitPath = (path: string): string[] => {7 let paths = splitPathCache[path]8 if (paths) {9 return paths10 }6 const paths = path.split(/\//) // faster than path.split('/')11 paths = path.split(/\//) // faster than path.split('/')12 if (paths[0] === '') {13 paths.shift()14 }15 splitPathCache[path] = paths16 return paths17}1819const patternCache: { [key: string]: Pattern } = {}
26 unmodified lines
46type Params = {47 strict: boolean48}4950const pathFromURLCache: Record<string, string> = {}51export const getPathFromURL = (url: string, params: Params = { strict: true }): string => {52 // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same53 // default is true54 if (params.strict === false && url.endsWith('/')) {55 url = url.slice(0, -1)56 }5758 let path = pathFromURLCache[url]59 if (path) return path6061 const match = url.match(URL_REGEXP)52 if (match) {53 return match[1]54 }55 return ''62 path = match ? match[1] : ''63 pathFromURLCache[url] = path64 return path65}6667export const isAbsoluteURL = (url: string): boolean => {68 const match = url.match(URL_REGEXP)
37 unmodified lines