Repository navigation
Expand file tree
/
Copy pathutil.ts
More file actions
65 lines (55 loc) · 1.58 KB
/
Copy pathutil.ts
File metadata and controls
65 lines (55 loc) · 1.58 KB
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
62
63
64
65
/**
* @file common util
* @author netcon
*/
export const noop = () => {};
export const isNil = (value: any) => value === undefined || value === null;
export const trimStart = (str: string, chars: string = ' '): string => {
let index = 0;
while (chars.indexOf(str[index]) !== -1) {
index++;
}
return str.slice(index);
};
export const trimEnd = (str: string, chars: string = ' '): string => {
let length = str.length;
while (length && chars.indexOf(str[length - 1]) !== -1) {
length--;
}
return str.slice(0, length);
};
export const joinPath = (...segments: string[]): string => {
const validSegments = segments.filter(Boolean);
if (!validSegments.length) {
return '';
}
return validSegments.reduce((prev, segment) => {
return trimEnd(prev, '/') + '/' + trimStart(segment, '/');
});
};
export const dirname = (path: string): string => {
const trimmedPath = trimEnd(path, '/');
return trimmedPath.substr(0, trimmedPath.lastIndexOf('/')) || '';
};
export const basename = (path: string): string => {
const trimmedPath = trimEnd(path, '/');
return trimmedPath.substr(trimmedPath.lastIndexOf('/') + 1) || '';
};
export const uniqueId = (
(id) => () =>
id++
)(1);
export const prop = (obj: object, path: (string | number)[] = []): any => {
let cur = obj;
path.forEach((key) => (cur = cur ? cur[key] : undefined));
return cur;
};
export const last = <T>(array: readonly T[]): T => {
return array[array.length - 1];
};
export const encodeFilePath = (filePath: string): string => {
return filePath
.split('/')
.map((segment) => encodeURIComponent(segment))
.join('/');
};