Problems › JavaScript › patterns
Tidy up a file path
A storage service is handed paths with stray slashes and dot segments in them, and stores exactly one canonical form.
- Segments are separated by slashes; runs of slashes count as one.
- A "." segment means "here" and is dropped.
- A ".." segment climbs one level; at the root it does nothing.
- The result starts with a slash and, apart from the root, does not end with one.
- The root itself is a single slash.
tidyPath(raw: string) → string
Where you start
function tidyPath(raw) {
}
Worked examples
| Call | Result |
|---|---|
tidyPath("/home//user/") | "/home/user" |
tidyPath("/a/./b/../c") | "/a/c" |
tidyPath("/../") | "/" |
tidyPath("/") | "/" |
Hint
Split on the slash and push each real segment onto a stack; ".." pops instead. Joining the stack back up gives the answer.
Reference solution in JavaScript
function tidyPath(raw) {
const kept = [];
for (const part of raw.split("/")) {
if (part === "" || part === ".") continue;
if (part === "..") kept.pop();
else kept.push(part);
}
return "/" + kept.join("/");
}