0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-03-04 09:57:11 -05:00

fix(ext/node): use primordials in ext/node/polyfills/path/common.ts (#28164)

Related to https://github.com/denoland/deno/issues/24236
This commit is contained in:
Rajhans Jadhao 2025-02-18 17:21:14 +05:30 committed by GitHub
parent f2a8c300d4
commit 45777b8eca
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,9 +1,16 @@
// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.
// TODO(petamoriken): enable prefer-primordials for node polyfills
// deno-lint-ignore-file prefer-primordials
import { primordials } from "ext:core/mod.js";
const {
StringPrototypeSubstring,
StringPrototypeLastIndexOf,
StringPrototypeSplit,
ArrayPrototypeSlice,
StringPrototypeEndsWith,
ArrayPrototypeJoin,
SafeArrayIterator,
} = primordials;
import { SEP } from "ext:deno_node/path/separator.ts";
/** Determines the common path from a set of paths, using an optional separator,
@ -18,15 +25,19 @@ import { SEP } from "ext:deno_node/path/separator.ts";
* ```
*/
export function common(paths: string[], sep = SEP): string {
const [first = "", ...remaining] = paths;
const [first = "", ...remaining] = new SafeArrayIterator(paths);
if (first === "" || remaining.length === 0) {
return first.substring(0, first.lastIndexOf(sep) + 1);
return StringPrototypeSubstring(
first,
0,
StringPrototypeLastIndexOf(first, sep) + 1,
);
}
const parts = first.split(sep);
const parts = StringPrototypeSplit(first, sep);
let endOfPrefix = parts.length;
for (const path of remaining) {
const compare = path.split(sep);
for (const path of new SafeArrayIterator(remaining)) {
const compare = StringPrototypeSplit(path, sep);
for (let i = 0; i < endOfPrefix; i++) {
if (compare[i] !== parts[i]) {
endOfPrefix = i;
@ -37,6 +48,9 @@ export function common(paths: string[], sep = SEP): string {
return "";
}
}
const prefix = parts.slice(0, endOfPrefix).join(sep);
return prefix.endsWith(sep) ? prefix : `${prefix}${sep}`;
const prefix = ArrayPrototypeJoin(
ArrayPrototypeSlice(parts, 0, endOfPrefix),
sep,
);
return StringPrototypeEndsWith(prefix, sep) ? prefix : `${prefix}${sep}`;
}