Skip to content

Commit 55b7d0a

Browse files
committed
feat: Add paths.ts with tests
1 parent a95c344 commit 55b7d0a

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

src/generate/paths.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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+
}

src/test/paths.test.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import * as assert from 'assert';
2+
3+
import { commonPath } from '../generate/paths';
4+
5+
describe('Path handling', function() {
6+
describe('#commonPath()', function() {
7+
it('should give the highest common parent directory for 3 related paths', function() {
8+
const paths = [
9+
'/home/user1/tmp/coverage/test',
10+
'/home/user1/tmp/covert/operator',
11+
'/home/user1/tmp/coven/members'
12+
];
13+
14+
assert.equal(commonPath(paths), '/home/user1/tmp');
15+
});
16+
17+
it('should give the highest common parent directory for two different paths', function() {
18+
const paths = [ '/foo/test', '/foo/bar/test' ];
19+
20+
assert.equal(commonPath(paths), '/foo');
21+
});
22+
23+
it('should give the highest common parent directory for two similar', function() {
24+
const paths = [ '/fizz', '/buzz' ];
25+
26+
assert.equal(commonPath(paths), '');
27+
});
28+
});
29+
});

0 commit comments

Comments
 (0)