Explorer
Node.js

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" }; } }; } ```

Build a Simple Router

Hard
Create a `createRouter()` with `addRoute(method, path, handler)` and `handle(method, path)` that matches routes and calls the handler.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[{"status":200,"data":["Alice","Bob"]},{"status":404,"message":"Not Found"}]