Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(path): fix common() results that depend on the order and/or number of input paths #4414

Merged
merged 2 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions path/_common/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,24 @@

export function _common(paths: string[], sep: string): string {
const [first = "", ...remaining] = paths;
if (first === "" || remaining.length === 0) {
return first.substring(0, first.lastIndexOf(sep) + 1);
}
const parts = first.split(sep);

let endOfPrefix = parts.length;
let append = "";
for (const path of remaining) {
const compare = path.split(sep);
if (compare.length <= endOfPrefix) {
endOfPrefix = compare.length;
append = "";
}

for (let i = 0; i < endOfPrefix; i++) {
if (compare[i] !== parts[i]) {
endOfPrefix = i;
append = i === 0 ? "" : sep;
break;
}
}

if (endOfPrefix === 0) {
return "";
}
}
const prefix = parts.slice(0, endOfPrefix).join(sep);
return prefix.endsWith(sep) ? prefix : `${prefix}${sep}`;
return parts.slice(0, endOfPrefix).join(sep) + append;
}
42 changes: 42 additions & 0 deletions path/common_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,45 @@ Deno.test({
assertEquals(actual, "c:\\deno\\");
},
});

Deno.test({
name: "common(['', '/'], '/') returns ''",
fn() {
const actual = common(["", "/"], "/");
assertEquals(actual, "");
},
});

Deno.test({
name: "common(['/', ''], '/') returns ''",
fn() {
const actual = common([
"/",
"",
], "/");
assertEquals(actual, "");
},
});

Deno.test({
name: "common() returns the first path unmodified when it's the only path",
fn() {
const actual = common(["./deno/std/path/mod.ts"], "/");
assertEquals(actual, "./deno/std/path/mod.ts");
},
});

Deno.test({
name: "common() returns the first path unmodified if all paths are equal",
fn() {
const actual = common(
[
"./deno/std/path/mod.ts",
"./deno/std/path/mod.ts",
"./deno/std/path/mod.ts",
],
"/",
);
assertEquals(actual, "./deno/std/path/mod.ts");
},
});
Loading