summaryrefslogtreecommitdiff
path: root/cli/js/util.ts
diff options
context:
space:
mode:
Diffstat (limited to 'cli/js/util.ts')
-rw-r--r--cli/js/util.ts30
1 files changed, 30 insertions, 0 deletions
diff --git a/cli/js/util.ts b/cli/js/util.ts
index 013dc7ee1..77dc7db5b 100644
--- a/cli/js/util.ts
+++ b/cli/js/util.ts
@@ -223,3 +223,33 @@ export function splitNumberToParts(n: number): number[] {
const higher = (n - lower) / 0x100000000;
return [lower, higher];
}
+
+/** Return the common path shared by the `paths`.
+ *
+ * @param paths The set of paths to compare.
+ * @param sep An optional separator to use. Defaults to `/`.
+ * @internal
+ */
+export function commonPath(paths: string[], sep = "/"): string {
+ const [first = "", ...remaining] = paths;
+ if (first === "" || remaining.length === 0) {
+ return "";
+ }
+ const parts = first.split(sep);
+
+ let endOfPrefix = parts.length;
+ for (const path of remaining) {
+ const compare = path.split(sep);
+ for (let i = 0; i < endOfPrefix; i++) {
+ if (compare[i] !== parts[i]) {
+ endOfPrefix = i;
+ }
+ }
+
+ if (endOfPrefix === 0) {
+ return "";
+ }
+ }
+ const prefix = parts.slice(0, endOfPrefix).join(sep);
+ return prefix.endsWith(sep) ? prefix : `${prefix}${sep}`;
+}