@b08/route-matcher
v1.0.2
Published
Utility to match url against routes
Downloads
16
Readme
@b08/route-matcher, seeded from @b08/library-seed, library type: feature
Utility to match url against routes. Performance of this method is O(m) instead of O(n), where n is a number of routes, m is a number of slash-separated segments in url.
usage
Routes are preprocessed for fast search and memoized. Beware not to call the method with different array of routes every time. Several routes might match the url, it is up to you to throw or ignore.
import { IMap } from "@b08/object-map";
import { matchRoute } from "@b08/route-matcher";
const myRoutes = [
{ route: "/", action: () => openHomePage() },
{ route: "/dashboard/:userId", action: (parameters: IMap) => openDashboardPage(parameters["userId"]) }
];
function navigate(url: string): void {
const routes = findMatchingRoutes(url, myRoutes);
if(routes.length === 0) {
open(404);
return;
}
const firstRoute = routes[0];
firstRoute.route.action(firstRoute.parameters);
}
optional parameters
Parameter name trailing with question mark is optional, example "/dashboard/:userId?". Will match both url's "/dashboard/123" and "/dashboard"