|
| 1 | +/** |
| 2 | + * Find common parent directory of paths. |
| 3 | + * |
| 4 | + * From: http://rosettacode.org/wiki/Find_common_directory_path#JavaScript |
| 5 | + * |
| 6 | + * JS does not have a builtin function like Python does. |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * Given an array of strings, return an array of arrays, containing the |
| 11 | + * strings split at the given separator |
| 12 | + * |
| 13 | + * @param {!Array<!string>} a |
| 14 | + * @param {string} sep |
| 15 | + * @returns {!Array<!Array<string>>} |
| 16 | + */ |
| 17 | +const splitStrings = (a: any[], sep = '/') => |
| 18 | + a.map((i: string) => i.split(sep)); |
| 19 | + |
| 20 | +/** |
| 21 | + * Given an index number, return a function that takes an array and returns the |
| 22 | + * element at the given index |
| 23 | + * |
| 24 | + * @param {number} i |
| 25 | + * @return {function(!Array<*>): *} |
| 26 | + */ |
| 27 | +function elAt(i: number) { |
| 28 | + return (a: { [x: string]: any }) => a[i]; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Transpose an array of arrays: |
| 33 | + * |
| 34 | + * Example: |
| 35 | + * [['a', 'b', 'c'], ['A', 'B', 'C'], [1, 2, 3]] -> |
| 36 | + * [['a', 'A', 1], ['b', 'B', 2], ['c', 'C', 3]] |
| 37 | + * |
| 38 | + * @param {!Array<!Array<*>>} a |
| 39 | + * @return {!Array<!Array<*>>} |
| 40 | + */ |
| 41 | +function rotate(a: any[]) { |
| 42 | + return a[0].map((e: any, i: any) => a.map(elAt(i))); |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Checks of all the elements in the array are the same. |
| 47 | + * |
| 48 | + * @param {!Array<*>} arr |
| 49 | + * @return {boolean} |
| 50 | + */ |
| 51 | +function allElementsEqual(arr: any[]) { |
| 52 | + return arr.every((e: any) => e === arr[0]); |
| 53 | +} |
| 54 | + |
| 55 | +export function commonPath(input: string[], sep = '/') { |
| 56 | + return rotate(splitStrings(input, sep)) |
| 57 | + .filter(allElementsEqual) |
| 58 | + .map(elAt(0)) |
| 59 | + .join(sep); |
| 60 | +} |
0 commit comments