Skip to content

Create 0071-simplify-path.js #2614

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions javascript/0071-simplify-path.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

/**
* Stack
* Time O(N) | Space O(N)
* https://leetcode.com/problems/simplify-path
* @param {string} path
* @return {string}
*/
var simplifyPath = (path, slash = '/', stack = []) => {
const paths = path.split(slash).filter(Boolean);

for (const _path of paths) traversePath(_path, stack);

return `${slash}${stack.join(slash)}`;
};

const traversePath = (path, stack) => {
if (canPush(path)) return stack.push(path);

if (canPop(path, stack)) stack.pop();
};

const canPush = (path) => !(
isCurrentDirectory(path) ||
isParentDirectory(path)
);

const canPop = (path, stack) =>
isParentDirectory(path) &&
!isEmpty(stack);

const isCurrentDirectory = (path) => (path === '.');

const isParentDirectory = (path) => (path === '..');

const isEmpty = ({ length }) => (0 === length);