-
Notifications
You must be signed in to change notification settings - Fork 21
/
SimplifyPath.js
76 lines (65 loc) 路 1.65 KB
/
SimplifyPath.js
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
71
72
73
74
75
76
/**
* Given an absolute path for a file (Unix-style), simplify it.
*
* For example,
* path = "/home/", => "/home"
* path = "/a/./b/../../c/", => "/c"
*
* Corner Cases:
* Did you consider the case where path = "/../"?
* In this case, you should return "/".
* Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
* In this case, you should ignore redundant slashes and return "/home/foo".
*
* Accepted.
*/
/**
* @param {string} path
* @return {string}
*/
let simplifyPath = function (path) {
if (path == null || path.length === 0) {
return path;
}
let strings = path.split('/');
let stack = [];
for (let i = 1; i < strings.length; i++) {
if (strings[i] === "..") {
if (stack.length !== 0) {
stack.splice(stack.length - 1);
}
} else if (strings[i] !== "." && strings[i].length !== 0) {
stack.push(strings[i]);
}
}
let builder = "";
stack.forEach(function (s) {
builder = builder.concat("/", s);
});
return builder.length === 0 ? "/" : builder;
};
if (simplifyPath("/home/") === "/home") {
console.log("pass")
} else {
console.error("failed")
}
if (simplifyPath("/a/./b/../../c/") === "/c") {
console.log("pass")
} else {
console.error("failed")
}
if (simplifyPath("/../") === "/") {
console.log("pass")
} else {
console.error("failed")
}
if (simplifyPath("/home//foo/") === "/home/foo") {
console.log("pass")
} else {
console.error("failed")
}
if (simplifyPath("/a/b/c") === "/a/b/c") {
console.log("pass")
} else {
console.error("failed")
}