@lifaon/path
Version:
Useful tool to manage paths like the URL object
36 lines • 1.23 kB
JavaScript
/**
* Extracts the common base from many `IPathSegments`:
* - if no common base, returns `[]`
* - if common base is _absolute_, returns `['', ...]`
* - if common base is _relative_, returns `['..' | '.', ...]`
*/
export function getCommonBaseOfManyPathSegments(paths) {
const pathsLength = paths.length;
if (pathsLength === 0) {
throw new Error('Expected at least one path');
}
else {
if (pathsLength === 1) {
return paths[0].slice();
}
else {
const commonBase = [];
let segment;
let path;
let commonBaseLength;
while (true) {
commonBaseLength = commonBase.length;
path = paths[0];
segment = path[commonBaseLength];
for (let i = 1; i < pathsLength; i++) {
path = paths[i];
if (path.length <= commonBaseLength || path[commonBaseLength] !== segment) {
return commonBaseLength === 0 ? null : commonBase;
}
}
commonBase.push(segment);
}
}
}
}
//# sourceMappingURL=get-common-base-of-many-path-segments.js.map