type Route = | { name: "docs"; id: string } | { name: "settings" } | { name: "notfound"; path: string }; function parseHash(hash: string): Route { const clean = hash.replace(/^#\/?/, ""); if (clean === "settings") return { name: "settings" }; if (clean.startsWith("docs/")) { const id = clean.slice("docs/".length); if (id.length > 0 && !id.includes("/")) return { name: "docs", id }; } return { name: "notfound", path: clean }; } function hashOf(route: Route): string { if (route.name === "docs") return `#/docs/${route.id}`; if (route.name === "settings") return "#/settings"; return `#/${route.path}`; } const cases: Array<[string, Route]> = [ ["#/docs/intro", { name: "docs", id: "intro" }], ["#docs/intro", { name: "docs", id: "intro" }], ["#/settings", { name: "settings" }], ["#/docs/a/b", { name: "notfound", path: "docs/a/b" }], ["#/unknown", { name: "notfound", path: "unknown" }], ["", { name: "notfound", path: "" }], ]; const parsed = cases.map(([hash, expected]) => ({ hash, got: parseHash(hash), expected, ok: JSON.stringify(parseHash(hash)) === JSON.stringify(expected), })); const roundTrip = cases .map(([hash]) => parseHash(hash)) .filter((route) => route.name !== "notfound") .map((route) => ({ hash: hashOf(route), back: parseHash(hashOf(route)), ok: JSON.stringify(parseHash(hashOf(route))) === JSON.stringify(route), })); console.log( JSON.stringify({ evt: "smoke", ok: parsed.every((item) => item.ok) && roundTrip.every((item) => item.ok), parsed, roundTrip, }), );