Create a `createRouter()` with `addRoute(method, path, handler)` and `handle(method, path)` that matches routes and calls the handler.
Problem Statement
Create a `createRouter()` with `addRoute(method, path, handler)` and `handle(method, path)` that matches routes and calls the handler.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Store routes as an array of {method, path, handler} objects.
š” Hint 2:
handle() finds the first matching route by method and path.
š” Hint 3:
Return handler result if matched, or a 404 response if not.
ā
Solution:
```javascript
function createRouter() {
const routes = [];
return {
addRoute(method, path, handler) {
routes.push({ method: method.toUpperCase(), path, handler });
},
handle(method, path) {
const route = routes.find(r => r.method === method.toUpperCase() && r.path === path);
if (route) return route.handler();
return { status: 404, message: "Not Found" };
}
};
}
```