match

tcmts.react.match · #yvh4bn4g · term · runs anywhere

A path's parameters if it matches the pattern (/s/:owner/:key, /docs/*), decoded; undefined if it doesn't.

export function match(pattern: string, path: string): Record<string, string> | undefined {
  const want = pattern.split("/").filter(Boolean);
  const got = path.split("/").filter(Boolean);
  const out: Record<string, string> = {};
  try {
    for (let i = 0; i < want.length; i++) {
      const w = want[i]!;
      if (w === "*") {
        out["*"] = got.slice(i).map(decodeURIComponent).join("/");
        return out;
      }
      if (i >= got.length) return undefined;
      if (w.startsWith(":")) out[w.slice(1)] = decodeURIComponent(got[i]!);
      else if (w !== got[i]) return undefined;
    }
  } catch {
    // (a malformed escape isn't a path of the app's)
    return undefined;
  }
  return got.length === want.length ? out : undefined;
}

used by