-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPath.ts
70 lines (53 loc) · 1.92 KB
/
Path.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
62
63
64
65
66
67
68
69
70
export class Path extends String {
private constructor(...args: Parameters<typeof String>) {
super(...args);
}
static dirExp = /\/+/;
static fileExp = /\.(?!.*\.)/;
public static isAbsolute(src: Path): boolean {
return String.prototype.startsWith.call(src, '/');
}
public static isRelative(src: Path): boolean {
return String.prototype.startsWith.call(src, './') || String.prototype.startsWith.call(src, '../');
}
public static isDefault(src: Path): boolean {
return !(this.isAbsolute(src) || this.isRelative(src));
}
public static isPassive = this.isDefault;
public static isDirectory(src: Path): boolean { return String.prototype.endsWith.call(src, '/'); }
public static toSource(path: string[]): string {
return typeof path === 'string' ? path : path.join('/');
}
public static toArray(src: Path | string[]): string[] {
//@ts-ignore
if(typeof src !== 'string') return src;
return src === '/' ? [''] : src.split(this.dirExp);
}
public static normalize(src: Path, d: boolean = true) {
const path = this.toArray(src);
const normalized = [];
for(const i of path) {
if(i === '..') normalized.pop();
else if(i === '.') continue;
else normalized.push(i);
}
if(d && Path.isDirectory(src)) normalized.pop();
return this.toSource(normalized);
}
public static relative(src: Path, dir?: Path, d: boolean = true) {
const dira: string[] = dir ? this.toArray(dir) : [];
const path = this.isAbsolute(src) ? [...this.toArray(src)] : [...this.toArray(dira), ...this.toArray(src)];
return this.normalize(this.toSource(path), d);
}
public static file(src: Path) {
//@ts-ignore
const data: { filename: string; name: string; exp: string; dir: string; } = {};
const path = this.toArray(src);
data.filename = path.pop()!;
data.dir = path.length ? this.toSource(path)+'/' : '';
const [name, exp] = data.filename.split(this.fileExp);
data.name = name;
data.exp = exp;
return data;
}
}