Skip to content
Backend logic · Core · about 25 minutes

HTTP router

Implement createRouter(routes), where each route is [method, pattern, name] and a pattern is like /users/:id. It returns an object whose match(method, path) returns { route: name, params } for the first route, in list order, whose method and path match. A :name segment matches any one non-empty segment, and params holds those segments decoded with decodeURIComponent. Ignore a query string and a trailing slash. When the path matches some routes but none has this method, return { status: 405, allow } with their methods in route order, each once. When no path matches, return null. In the tests an op [at, method, ...args] calls that method at virtual time at (ms); the answer lists what each call returned.

Start from

function createRouter(routes) {
  // Return { match(method, path) } for these routes.
}

Hints

Each hint gives away a little more. Open one only when you need it.

  1. Hint 1

    Split the pattern and the path on / after dropping the query and the trailing slash; the segment counts must be equal.

  2. Hint 2

    Walk the segments together: a :name segment saves the path segment as a param, any other segment must be equal.

  3. Hint 3

    Keep the methods of routes whose path matched but whose method did not; if nothing matched fully, they decide between 405 and null.

Solution

The app has this lab in JavaScript, TypeScript and Python. This page shows the JavaScript code.

From here on the page gives the method away. If you are still solving, go back to the hints.

JavaScript
function createRouter(routes) {
  const parts = (path) => path.split("?")[0].split("/").filter((part, index, all) => index > 0 && !(part === "" && index === all.length - 1));
  const compiled = routes.map(([method, pattern, name]) => ({ method, name, parts: parts(pattern) }));
  function pathParams(route, segments) {
    if (route.parts.length !== segments.length) return null;
    const params = {};
    for (let i = 0; i < segments.length; i++) {
      const part = route.parts[i];
      if (part.startsWith(":")) {
        if (segments[i] === "") return null;
        params[part.slice(1)] = decodeURIComponent(segments[i]);
      } else if (part !== segments[i]) return null;
    }
    return params;
  }
  return {
    match(method, path) {
      const segments = parts(path);
      const allow = [];
      for (const route of compiled) {
        const params = pathParams(route, segments);
        if (!params) continue;
        if (route.method === method) return { route: route.name, params };
        if (!allow.includes(route.method)) allow.push(route.method);
      }
      return allow.length ? { status: 405, allow } : null;
    },
  };
}

What an interviewer looks for

Every web framework has a router, and 404 against 405 is a detail interviewers like. Writing one shows you know what a path parameter is and why route order matters.