Add utility function to join paths (#3060)

This commit is contained in:
Jon Koops 2022-08-05 15:46:51 +02:00 committed by GitHub
parent d1d7a4ae4e
commit 9ff8d83a43
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 0 deletions

View 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
View 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);
}