Add utility function to join paths (#3060)
This commit is contained in:
parent
d1d7a4ae4e
commit
9ff8d83a43
2 changed files with 45 additions and 0 deletions
23
src/utils/joinPath.test.ts
Normal file
23
src/utils/joinPath.test.ts
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { joinPath } from "./joinPath";
|
||||||
|
|
||||||
|
describe("joinPath", () => {
|
||||||
|
it("returns an empty string when no paths are provided", () => {
|
||||||
|
expect(joinPath()).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("joins paths", () => {
|
||||||
|
expect(joinPath("foo", "bar", "baz")).toBe("foo/bar/baz");
|
||||||
|
expect(joinPath("foo", "/bar", "baz")).toBe("foo/bar/baz");
|
||||||
|
expect(joinPath("foo", "bar/", "baz")).toBe("foo/bar/baz");
|
||||||
|
expect(joinPath("foo", "/bar/", "baz")).toBe("foo/bar/baz");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("joins paths with leading slashes", () => {
|
||||||
|
expect(joinPath("/foo", "bar", "baz")).toBe("/foo/bar/baz");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("joins paths with trailing slashes", () => {
|
||||||
|
expect(joinPath("foo", "bar", "baz/")).toBe("foo/bar/baz/");
|
||||||
|
});
|
||||||
|
});
|
22
src/utils/joinPath.ts
Normal file
22
src/utils/joinPath.ts
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
const PATH_SEPARATOR = "/";
|
||||||
|
|
||||||
|
export function joinPath(...paths: string[]) {
|
||||||
|
const normalizedPaths = paths.map((path, index) => {
|
||||||
|
const isFirst = index === 0;
|
||||||
|
const isLast = index === paths.length - 1;
|
||||||
|
|
||||||
|
// Strip out any leading slashes from the path.
|
||||||
|
if (!isFirst && path.startsWith(PATH_SEPARATOR)) {
|
||||||
|
path = path.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip out any trailing slashes from the path.
|
||||||
|
if (!isLast && path.endsWith(PATH_SEPARATOR)) {
|
||||||
|
path = path.slice(0, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return path;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return normalizedPaths.join(PATH_SEPARATOR);
|
||||||
|
}
|
Loading…
Reference in a new issue