Match URL Paths to Routes

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write matchPath(pattern, path), which checks a URL path against a route pattern and returns its params, or null if it doesn't match. Split both into segments at "/", ignoring empty segments, so leading, trailing and doubled slashes don't matter; in the path, anything from a "?" or "#" on is ignored too. In the pattern, a plain segment must equal the path's segment exactly, letter case included. ":name" matches any one segment and stores it as params.name, decoded with decodeURIComponent (a segment that can't be decoded, such as one with a broken % escape, is kept as written). ":name?" is optional: it takes a segment if one is left and is otherwise left out of params; optional parameters only come at the end of a pattern. A final "*" matches the rest of the path, zero or more segments, and stores them as params["*"], each decoded and joined with "/", or "" if there are none. Every segment of the path must be matched. Then write createRouter(routes), where each route is an object with a path pattern, returning { match(path) }: it gives { route, params } for the best matching route, or null. Score each pattern: 10 for each plain segment, 3 for each required parameter, -1 for each optional parameter and -2 for a wildcard (so /users/:id scores 13 and /users/:id/:tab? scores 12). The highest score wins, and a tie goes to the route listed first.

Your code must pass

  • Matches static paths and ignores extra slashes
  • Captures and decodes named parameters
  • Handles optional parameters
  • Captures the rest with a wildcard
  • Ignores the query string and hash
  • Picks the most specific route
  • Breaks ties by the order of the routes