Skip to content

Commit

Permalink
fix(path): fix common() results that depend on the order and/or numbe…
Browse files Browse the repository at this point in the history
…r of input paths (#4414)
  • Loading branch information
jviide authored Mar 5, 2024
1 parent cec0c68 commit 0c6f5e8
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 9 deletions.
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");
},
});

0 comments on commit 0c6f5e8

Please sign in to comment.