Skip to content

Commit

Permalink
refactor(router): use # for private props to reduce the minified fi…
Browse files Browse the repository at this point in the history
…le size (#3660)
  • Loading branch information
EdamAme-x authored Nov 12, 2024
1 parent 7e17b76 commit 7b30835
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 90 deletions.
8 changes: 4 additions & 4 deletions src/router/linear-router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,22 @@ const splitPathRe = /\/(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/[^\/\?]+|(\?)/g
const splitByStarRe = /\*/
export class LinearRouter<T> implements Router<T> {
name: string = 'LinearRouter'
routes: [string, string, T][] = []
#routes: [string, string, T][] = []

add(method: string, path: string, handler: T) {
for (
let i = 0, paths = checkOptionalParameter(path) || [path], len = paths.length;
i < len;
i++
) {
this.routes.push([method, paths[i], handler])
this.#routes.push([method, paths[i], handler])
}
}

match(method: string, path: string): Result<T> {
const handlers: [T, Params][] = []
ROUTES_LOOP: for (let i = 0, len = this.routes.length; i < len; i++) {
const [routeMethod, routePath, handler] = this.routes[i]
ROUTES_LOOP: for (let i = 0, len = this.#routes.length; i < len; i++) {
const [routeMethod, routePath, handler] = this.#routes[i]
if (routeMethod === method || routeMethod === METHOD_NAME_ALL) {
if (routePath === '*' || routePath === '/*') {
handlers.push([handler, emptyParams])
Expand Down
38 changes: 19 additions & 19 deletions src/router/reg-exp-router/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ function compareKey(a: string, b: string): number {
}

export class Node {
index?: number
varIndex?: number
children: Record<string, Node> = Object.create(null)
#index?: number
#varIndex?: number
#children: Record<string, Node> = Object.create(null)

insert(
tokens: readonly string[],
Expand All @@ -55,14 +55,14 @@ export class Node {
pathErrorCheckOnly: boolean
): void {
if (tokens.length === 0) {
if (this.index !== undefined) {
if (this.#index !== undefined) {
throw PATH_ERROR
}
if (pathErrorCheckOnly) {
return
}

this.index = index
this.#index = index
return
}

Expand All @@ -88,10 +88,10 @@ export class Node {
}
}

node = this.children[regexpStr]
node = this.#children[regexpStr]
if (!node) {
if (
Object.keys(this.children).some(
Object.keys(this.#children).some(
(k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
)
) {
Expand All @@ -100,19 +100,19 @@ export class Node {
if (pathErrorCheckOnly) {
return
}
node = this.children[regexpStr] = new Node()
node = this.#children[regexpStr] = new Node()
if (name !== '') {
node.varIndex = context.varIndex++
node.#varIndex = context.varIndex++
}
}
if (!pathErrorCheckOnly && name !== '') {
paramMap.push([name, node.varIndex as number])
paramMap.push([name, node.#varIndex as number])
}
} else {
node = this.children[token]
node = this.#children[token]
if (!node) {
if (
Object.keys(this.children).some(
Object.keys(this.#children).some(
(k) =>
k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
)
Expand All @@ -122,29 +122,29 @@ export class Node {
if (pathErrorCheckOnly) {
return
}
node = this.children[token] = new Node()
node = this.#children[token] = new Node()
}
}

node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly)
}

buildRegExpStr(): string {
const childKeys = Object.keys(this.children).sort(compareKey)
const childKeys = Object.keys(this.#children).sort(compareKey)

const strList = childKeys.map((k) => {
const c = this.children[k]
const c = this.#children[k]
return (
(typeof c.varIndex === 'number'
? `(${k})@${c.varIndex}`
(typeof c.#varIndex === 'number'
? `(${k})@${c.#varIndex}`
: regExpMetaChars.has(k)
? `\\${k}`
: k) + c.buildRegExpStr()
)
})

if (typeof this.index === 'number') {
strList.unshift(`#${this.index}`)
if (typeof this.#index === 'number') {
strList.unshift(`#${this.#index}`)
}

if (strList.length === 0) {
Expand Down
19 changes: 10 additions & 9 deletions src/router/reg-exp-router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,16 +123,17 @@ function findMiddleware<T>(

export class RegExpRouter<T> implements Router<T> {
name: string = 'RegExpRouter'
middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>
routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>
#middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>
#routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>

constructor() {
this.middleware = { [METHOD_NAME_ALL]: Object.create(null) }
this.routes = { [METHOD_NAME_ALL]: Object.create(null) }
this.#middleware = { [METHOD_NAME_ALL]: Object.create(null) }
this.#routes = { [METHOD_NAME_ALL]: Object.create(null) }
}

add(method: string, path: string, handler: T) {
const { middleware, routes } = this
const middleware = this.#middleware
const routes = this.#routes

if (!middleware || !routes) {
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)
Expand Down Expand Up @@ -232,14 +233,14 @@ export class RegExpRouter<T> implements Router<T> {
#buildAllMatchers(): Record<string, Matcher<T> | null> {
const matchers: Record<string, Matcher<T> | null> = Object.create(null)

Object.keys(this.routes!)
.concat(Object.keys(this.middleware!))
Object.keys(this.#routes!)
.concat(Object.keys(this.#middleware!))
.forEach((method) => {
matchers[method] ||= this.#buildMatcher(method)
})

// Release cache
this.middleware = this.routes = undefined
this.#middleware = this.#routes = undefined

return matchers
}
Expand All @@ -249,7 +250,7 @@ export class RegExpRouter<T> implements Router<T> {

let hasOwnRoute = method === METHOD_NAME_ALL

;[this.middleware!, this.routes!].forEach((r) => {
;[this.#middleware!, this.#routes!].forEach((r) => {
const ownRoute = r[method]
? Object.keys(r[method]).map((path) => [path, r[method][path]])
: []
Expand Down
8 changes: 4 additions & 4 deletions src/router/reg-exp-router/trie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { Node } from './node'
export type ReplacementMap = number[]

export class Trie {
context: Context = { varIndex: 0 }
root: Node = new Node()
#context: Context = { varIndex: 0 }
#root: Node = new Node()

insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamAssocArray {
const paramAssoc: ParamAssocArray = []
Expand Down Expand Up @@ -41,13 +41,13 @@ export class Trie {
}
}

this.root.insert(tokens, index, paramAssoc, this.context, pathErrorCheckOnly)
this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly)

return paramAssoc
}

buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {
let regexp = this.root.buildRegExpStr()
let regexp = this.#root.buildRegExpStr()
if (regexp === '') {
return [/^$/, [], []] // never match
}
Expand Down
26 changes: 14 additions & 12 deletions src/router/smart-router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,29 @@ import { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from '../../ro

export class SmartRouter<T> implements Router<T> {
name: string = 'SmartRouter'
routers: Router<T>[] = []
routes?: [string, string, T][] = []
#routers: Router<T>[] = []
#routes?: [string, string, T][] = []

constructor(init: Pick<SmartRouter<T>, 'routers'>) {
Object.assign(this, init)
constructor(init: { routers: Router<T>[] }) {
this.#routers = init.routers
}

add(method: string, path: string, handler: T) {
if (!this.routes) {
if (!this.#routes) {
throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)
}

this.routes.push([method, path, handler])
this.#routes.push([method, path, handler])
}

match(method: string, path: string): Result<T> {
if (!this.routes) {
if (!this.#routes) {
throw new Error('Fatal error')
}

const { routers, routes } = this
const routers = this.#routers
const routes = this.#routes

const len = routers.length
let i = 0
let res
Expand All @@ -42,8 +44,8 @@ export class SmartRouter<T> implements Router<T> {
}

this.match = router.match.bind(router)
this.routers = [router]
this.routes = undefined
this.#routers = [router]
this.#routes = undefined
break
}

Expand All @@ -59,10 +61,10 @@ export class SmartRouter<T> implements Router<T> {
}

get activeRouter(): Router<T> {
if (this.routes || this.routers.length !== 1) {
if (this.#routes || this.#routers.length !== 1) {
throw new Error('No active router has been determined yet.')
}

return this.routers[0]
return this.#routers[0]
}
}
Loading

0 comments on commit 7b30835

Please sign in to comment.