Skip to content

Commit f65d073

Browse files
authoredJul 4, 2023
Update 0071-simplify-path.js
Modularizing the code.
1 parent 7bd673b commit f65d073

File tree

1 file changed

+30
-25
lines changed

1 file changed

+30
-25
lines changed
 

‎javascript/0071-simplify-path.js

+30-25
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,36 @@
1+
12
/**
23
* Stack
3-
* https://leetcode.com/problems/simplify-path/
4-
*
5-
* Time O(n) | Space O(n)
4+
* Time O(N) | Space O(N)
5+
* https://leetcode.com/problems/simplify-path
66
* @param {string} path
77
* @return {string}
88
*/
9-
var simplifyPath = function(path) {
10-
let currunt = '';
11-
let myStack = [];
12-
path = `/${path}/`;
13-
for(let i = 0; i < path.length; i++) {
14-
15-
if(path[i] === '/') {
16-
if(currunt == '..') {
17-
myStack.pop();
18-
} else if(currunt !== '' && currunt !== '.') {
19-
myStack.push(currunt);
20-
}
21-
currunt = '';
22-
} else {
23-
currunt += path[i];
24-
}
25-
26-
}
27-
28-
myStack = myStack.join('/');
29-
myStack = '/' + myStack;
30-
return myStack;
9+
var simplifyPath = (path, slash = '/', stack = []) => {
10+
const paths = path.split(slash).filter(Boolean);
11+
12+
for (const _path of paths) traversePath(_path, stack);
13+
14+
return `${slash}${stack.join(slash)}`;
15+
};
16+
17+
const traversePath = (path, stack) => {
18+
if (canPush(path)) return stack.push(path);
19+
20+
if (canPop(path, stack)) stack.pop();
3121
};
22+
23+
const canPush = (path) => !(
24+
isCurrentDirectory(path) ||
25+
isParentDirectory(path)
26+
);
27+
28+
const canPop = (path, stack) =>
29+
isParentDirectory(path) &&
30+
!isEmpty(stack);
31+
32+
const isCurrentDirectory = (path) => (path === '.');
33+
34+
const isParentDirectory = (path) => (path === '..');
35+
36+
const isEmpty = ({ length }) => (0 === length);

0 commit comments

Comments
 (0)
Please sign in to comment.