Better way of finding element from map
Im making an api and all routes are stored in a map. is there a better and more optimised way to look if the route exists and to get it?
handleRequest(req: Request, info: Deno.ServeHandlerInfo): Response {
const path = new URL(req.url).pathname;
const route = this.getRoute(path);
if (!route) return new Response("not found", {status: 404});
console.log(route);
return new Response("Hello World!");
}
getRoute(pathname: string): Route | undefined {
const paths = pathname.split("/").filter(val => val.length > 0);
const path = paths.join("/");
let routes = Array.from(this.routes.keys());
for (const route of routes) {
const regex = new RegExp(`^(${route.replaceAll(/\[.*\]/g, "(.*)")})$`)
if (!regex.test(path)) continue;
return this.routes.get(route);
}
}handleRequest(req: Request, info: Deno.ServeHandlerInfo): Response {
const path = new URL(req.url).pathname;
const route = this.getRoute(path);
if (!route) return new Response("not found", {status: 404});
console.log(route);
return new Response("Hello World!");
}
getRoute(pathname: string): Route | undefined {
const paths = pathname.split("/").filter(val => val.length > 0);
const path = paths.join("/");
let routes = Array.from(this.routes.keys());
for (const route of routes) {
const regex = new RegExp(`^(${route.replaceAll(/\[.*\]/g, "(.*)")})$`)
if (!regex.test(path)) continue;
return this.routes.get(route);
}
}