zerobyte/packages/core/src/utils/common-ancestor.ts
Nico 332e5bffda
refactor: extract restic in core package (#651)
* refactor: extract restic in core package

* chore: add turbo task runner

* refactor: split server utils

* chore: simplify withDeps signature and fix non-null assertion
2026-03-11 21:56:07 +01:00

26 lines
725 B
TypeScript

export const findCommonAncestor = (paths: string[]): string => {
for (const p of paths) {
if (!p.startsWith("/")) {
throw new Error(`Path "${p}" is not absolute.`);
}
}
if (paths.length === 0) return "/";
if (paths.length === 1) return paths[0] || "/";
const splitPaths = paths.map((path) => path.split("/").filter(Boolean));
const minLength = Math.min(...splitPaths.map((parts) => parts.length));
const commonParts: string[] = [];
for (let i = 0; i < minLength; i++) {
const partSet = new Set(splitPaths.map((parts) => parts[i]));
const toPush = splitPaths[0]?.[i];
if (partSet.size === 1 && toPush) {
commonParts.push(toPush);
} else {
break;
}
}
return "/" + commonParts.join("/");
};