export const normalizePath = (path: string): string => path.replace(/\\/g, '/');
export const isAbsolutePath = (path: string): boolean => path.includes('/') || path.includes('\\');
export const mergeSimilarDirectories = (directories: string[]): string[] => {
if (directories.length <= 1) return directories;
const absolutePaths = new Map<string, string>();
const relativePaths = new Set<string>();
directories.forEach((dir) => {
if (isAbsolutePath(dir)) {
const normalized = normalizePath(dir);
if (!absolutePaths.has(normalized)) {
absolutePaths.set(normalized, dir);
}
} else {
relativePaths.add(dir);
}
});
const sortedAbsolutePaths = Array.from(absolutePaths.keys()).sort((a, b) => a.length - b.length);
const mergedAbsolutePaths = new Set<string>();
for (const path of sortedAbsolutePaths) {
const hasParent = Array.from(mergedAbsolutePaths).some((existing) => path.startsWith(`${existing}/`));
if (!hasParent) {
mergedAbsolutePaths.add(absolutePaths.get(path)!);
}
}
const mergedRelativePaths = Array.from(relativePaths).filter((relPath) => {
return !Array.from(mergedAbsolutePaths).some((absPath) => {
const normalized = normalizePath(absPath);
return normalized.endsWith(`/${relPath}`) || normalized.includes(`/${relPath}/`);
});
});
return [...mergedAbsolutePaths, ...mergedRelativePaths];
};