-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathjoin.ts
More file actions
51 lines (43 loc) · 1.31 KB
/
join.ts
File metadata and controls
51 lines (43 loc) · 1.31 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
import { isString } from "../../lang";
/**
* Joins all given path segments into a single normalized path string.
*
* @param {...string} paths - A variable number of string path segments to join.
* @returns {string} A new string representing the joined, normalized, and URL-encoded path.
* @since 1.0.0
* @version 1.0.0
* @environment `Google Apps Script`, `Browser`
*/
export function join(...paths: string[]): string {
const resolvedParts: string[] = [];
let isAbsoluteResult = false;
for (const path of paths) {
if (!isString(path)) {
continue;
}
if (path.startsWith("/")) {
resolvedParts.length = 0;
isAbsoluteResult = true;
}
const segments = path.split("/").filter(Boolean);
for (const segment of segments) {
if (segment === ".") {
continue;
}
if (segment === "..") {
if (resolvedParts.length > 0 && resolvedParts[resolvedParts.length - 1] !== "..") {
resolvedParts.pop();
} else if (!isAbsoluteResult) {
resolvedParts.push("..");
}
} else {
resolvedParts.push(encodeURIComponent(segment));
}
}
}
if (isAbsoluteResult) {
return "/" + resolvedParts.join("/");
} else {
return resolvedParts.length === 0 ? "." : resolvedParts.join("/");
}
}