refactor: move mergePaths() to utils.ts (#2905)

This commit is contained in:
Tim Reichen
2025-05-12 09:59:37 +02:00
committed by GitHub
parent c6d4c47e00
commit 9605cd81b5
5 changed files with 33 additions and 32 deletions
+19
View File
@@ -13,3 +13,22 @@ export function assertInDir(
throw new Error(`Path "${tmp}" resolved outside of "${dir}"`);
}
}
/**
* Joins two path segments into a single normalized path.
* @example
* ```ts
* mergePaths("/api", "users"); // "/api/users"
* mergePaths("/api/", "/users"); // "/api/users"
* mergePaths("/", "/users"); // "/users"
* mergePaths("", "/users"); // "/users"
* mergePaths("/api", "/users"); // "/api/users"
* ```
*/
export function mergePaths(a: string, b: string) {
if (a === "" || a === "/" || a === "/*") return b;
if (b === "/") return a;
if (a.endsWith("/")) return a.slice(0, -1) + b;
if (!b.startsWith("/")) return a + "/" + b;
return a + b;
}