0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 10:51:01 +00:00
hono/deno_dist/router/reg-exp-router/trie.ts
Taku Amano d12a11937b
feat: Lightweight RegExpRouter reborn (#519)
* Introduce RegExpLiteRouter.

* Replace RegExpRouter with RegExpLiteRouter.

* chore: denoify

* Remove old RegExpRouter and rename RegExpLiteRouter to RegExpRouter.

* chore: Update benchmarks/handle-event.
2022-09-14 08:01:14 +09:00

50 lines
1.4 KiB
TypeScript

import type { ParamMap, Context } from './node.ts'
import { Node } from './node.ts'
export type { ParamMap } from './node.ts'
export type ReplacementMap = number[]
export class Trie {
context: Context = { varIndex: 0 }
root: Node = new Node()
insert(path: string, index: number): ParamMap {
const paramMap: ParamMap = []
/**
* - pattern (:label, :label{0-9]+}, ...)
* - /* wildcard
* - character
*/
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g)
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.root.insert(tokens, index, paramMap, this.context)
return paramMap
}
buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {
let regexp = this.root.buildRegExpStr()
let captureIndex = 0
const indexReplacementMap: ReplacementMap = []
const paramReplacementMap: ReplacementMap = []
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
if (typeof handlerIndex !== 'undefined') {
indexReplacementMap[++captureIndex] = Number(handlerIndex)
return '$()'
}
if (typeof paramIndex !== 'undefined') {
paramReplacementMap[Number(paramIndex)] = ++captureIndex
return ''
}
return ''
})
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]
}
}