chore: joinSegments fix + tests

This commit is contained in:
Jacky Zhao 2025-01-01 12:11:16 -08:00
parent 9466c145b1
commit e3162f7a7e
2 changed files with 37 additions and 7 deletions

View file

@ -158,6 +158,25 @@ describe("transforms", () => {
path.isRelativeURL, path.isRelativeURL,
) )
}) })
test("joinSegments", () => {
assert.strictEqual(path.joinSegments("a", "b"), "a/b")
assert.strictEqual(path.joinSegments("a/", "b"), "a/b")
assert.strictEqual(path.joinSegments("a", "b/"), "a/b/")
assert.strictEqual(path.joinSegments("a/", "b/"), "a/b/")
// preserve leading and trailing slashes
assert.strictEqual(path.joinSegments("/a", "b"), "/a/b")
assert.strictEqual(path.joinSegments("/a/", "b"), "/a/b")
assert.strictEqual(path.joinSegments("/a", "b/"), "/a/b/")
assert.strictEqual(path.joinSegments("/a/", "b/"), "/a/b/")
// works with protocol specifiers
assert.strictEqual(path.joinSegments("https://example.com", "a"), "https://example.com/a")
assert.strictEqual(path.joinSegments("https://example.com/", "a"), "https://example.com/a")
assert.strictEqual(path.joinSegments("https://example.com", "a/"), "https://example.com/a/")
assert.strictEqual(path.joinSegments("https://example.com/", "a/"), "https://example.com/a/")
})
}) })
describe("link strategies", () => { describe("link strategies", () => {

View file

@ -183,15 +183,26 @@ export function slugTag(tag: string) {
} }
export function joinSegments(...args: string[]): string { export function joinSegments(...args: string[]): string {
return args if (args.length === 0) {
return ""
}
let joined = args
.filter((segment) => segment !== "") .filter((segment) => segment !== "")
.map((segment, index) => .map((segment) => stripSlashes(segment))
index === 0
? // Deduplicate but not remove leading slashes for first segment
segment.replace(/\/+$/g, "").replace(/^\/\/+/g, "/")
: segment.replace(/^\/+|\/+$/g, ""),
)
.join("/") .join("/")
// if the first segment starts with a slash, add it back
if (args[0].startsWith("/")) {
joined = "/" + joined
}
// if the last segment is a folder, add a trailing slash
if (args[args.length - 1].endsWith("/")) {
joined = joined + "/"
}
return joined
} }
export function getAllSegmentPrefixes(tags: string): string[] { export function getAllSegmentPrefixes(tags: string): string[] {