-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathutil.ts
61 lines (55 loc) · 2.08 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { Pathname } from '@cycle/history';
import { LocationDescriptorObject } from 'history';
function splitPath(path: Pathname): Pathname[] {
if (!path) {
return [];
}
return path.split('/').filter(p => p.length > 0);
}
function filterPath(pathParts: Pathname[], namespace: Pathname[]): Pathname {
return pathParts.filter(part => namespace.indexOf(part) < 0).join('/');
}
const startsWith = (param: string, value: string) => param[0] === value;
const startsWith2 = (param: string, value1: string, value2: string) =>
param[0] === value1 && param[1] === value2;
function makeCreateHref(
namespace: Pathname[],
_createHref: (pathname: LocationDescriptorObject) => Pathname
) {
/**
* Function used to create HREFs that are properly namespaced
* @typedef {createHref}
* @name createHref
* @method createHref
* @param {string} path - the HREF that will be appended to the current
* namespace
* @return {string} a fully qualified HREF composed from the current
* namespace and the path provided
*/
return function createHref(
location: Pathname | LocationDescriptorObject
): Pathname {
if (typeof location === 'object' && location !== null) {
const fullPath = `${namespace.join('/')}${location.pathname}`;
return startsWith(fullPath, '/') || startsWith2(fullPath, '#', '/')
? _createHref({
...location,
pathname: fullPath
})
: _createHref({
...location,
pathname: '/' + fullPath
});
} else if (typeof location === 'string') {
const fullPath = `${namespace.join('/')}${location}`;
return startsWith(fullPath, '/') || startsWith2(fullPath, '#', '/')
? _createHref({
pathname: fullPath
})
: _createHref({
pathname: '/' + fullPath
});
}
};
}
export { splitPath, filterPath, makeCreateHref };