A tiny(3kb) foundation for building fast router via Radix Tree strategy , high-performance alternative for famous path-to-regexp。
You can use it both in browser or Node.js.
Install
npm i path-to-tree
Usage
const ptt = ; const tree = tree; const param = tree /** * ==> { * param: { * id: "1" * } , * marker: 2 * } * * /
API
ptt( routeMap )
create tree instance
param
- routeMap: route map to add
const tree =
as same as
const tree = treetree
tree.add( route, marker [, option ])
add a route pattern
- route: route string like
/api/blog/:id
- marker: route marker which will return by find
- option: route config
- strict: when false , trailing delimiter is optional. (default: true)
- end: when false, only match the prefix of the URL (default: true)
const ptt = ; const tree = ; tree
tree.find( path )
- return : a object container marker and param
let ret = tree; ret // => {id: "1"} // marker ===
support param
- named param:
'/api/blog/:id
- anonymous param:
'/api/(hello|world)'
- optional param:
/api/name-:id?
、/api/name-(id|co)?
- complex param:
/blog/dada-((?:hello|nice)?-world)
Example
Simple Koa Router
const ptt = // === require('path-to-tree') { const tree = ; return { const match = tree if match ctxparam = matchparam; await match else await ; }} const Koa = ;const app = ; app app
Benchmark
router based on path-to-regexp , described as O(n) Time Complexity ( n means route's length )
By contrast, router based on path-to-tree described as O(1) Time Complexity .(consider the deepth of path as constant)
In my computer (MacBook Pro 15: 2.2 GHz Intel Core i7、16 GB 1600 MHz DDR3) , the result of the benchmark show as below.
size of routes is 3000, 200x fast
path-to-tree x 215 ops/sec ±0.45% (77 runs sampled)
path-to-regexp x 1.04 ops/sec ±0.39% (7 runs sampled)
Fastest is path-to-tree