Kay
Kay13mo ago

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);
}

}
2 Replies
NeTT
NeTT13mo ago
Why not store the regex string (or better, the regex itself) as the key for the map so that you don't need to do a route.replaceAll() on it everytime? Meanwhile the loop can use Map.prototype.entries() and become something like
for (const [route, val] of this.routes.entries()) {
const regex = new RegExp(`^(${route.replaceAll(/\[.*\]/g, "(.*)")})$`)
if (regex.test(path)) {
return val;
}
}
for (const [route, val] of this.routes.entries()) {
const regex = new RegExp(`^(${route.replaceAll(/\[.*\]/g, "(.*)")})$`)
if (regex.test(path)) {
return val;
}
}
Kay
KayOP13mo ago
thx

Did you find this page helpful?