UNPKG

@redocly/theme

Version:

Shared UI components lib

52 lines (46 loc) 1.41 kB
/** * Splits a file path into its directory components, removing the file name. * @param path - The full file path. * @returns An array of directories. */ function splitPath(path: string): string[] { const parts = path.split('/').filter(Boolean); parts.pop(); return parts; } /** * Finds the longest common prefix between two paths. * @param path1 - The first path as an array of directories. * @param path2 - The second path as an array of directories. * @returns An array representing the common prefix. */ function findCommonPrefix(path1: string[], path2: string[]): string[] { const common: string[] = []; for (let i = 0; i < Math.min(path1.length, path2.length); i++) { if (path1[i] === path2[i]) { common.push(path1[i]); } else { break; } } return common; } /** * Finds the closest common directory for a set of file paths. * @param paths - An array of absolute file paths. * @returns The closest common directory as a string. */ export function findClosestCommonDirectory(paths: string[]): string { if (paths.length === 0) { return '/'; } const splitPaths = paths.map(splitPath); let commonPrefix = splitPaths[0]; for (let i = 1; i < splitPaths.length; i++) { commonPrefix = findCommonPrefix(commonPrefix, splitPaths[i]); if (commonPrefix.length === 0) { return '/'; } } return '/' + commonPrefix.join('/'); }