Simple pathname router that makes zero assumptions about the server.
npm install @borderless/router --save-dev
export declare function createRouter(
routes: string[]
): (pathname: string) => Iterable<Result>;
Exposes a simple createRouter
function that accepts a list of routes. It returns a function that accepts the pathname as input and returns an iterable of results. Results are an object containing the route
that matched, and list keys
and values
(if any) that were extracted from dynamic matches.
import { createRouter } from "@borderless/router";
const router = createRouter([
"a",
"b",
"[param]",
"@[param]",
"[param1]/[param2]",
]);
const results = Array.from(router("a"));
expect(results).toEqual([
{ route: "a", keys: [], values: [] },
{ route: "[param]", keys: ["param"], values: ["a"] },
]);
Since the result is an iterable, if you only want the first match you can discard the iterable to stop computing results.
const results = router("a");
for (const result of results) {
console.log(result); //=> { route: "a", keys: [], values: [] }
break;
}
The routes are pre-sorted to match the most specific routes first (i.e. static routes or most segments), it is not based on the input order. The internal representation is a trie.
This project is written using TypeScript and publishes the definitions directly to NPM.
MIT