Drill

ProblemsTypeScript › patterns

Tidy up a file path

hardpatternsStacksStringsParsingTypeScript

A storage service is handed paths with stray slashes and dot segments in them, and stores exactly one canonical form.

tidyPath(raw: string) → string

Solve it in the editor →

Where you start

function tidyPath(raw: string): string {
  
}

Worked examples

CallResult
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 TypeScript
function tidyPath(raw: string): string {
  const kept: string[] = [];
  for (const part of raw.split("/")) {
    if (part === "" || part === ".") continue;
    if (part === "..") kept.pop();
    else kept.push(part);
  }
  return "/" + kept.join("/");
}

The same problem in another language

More patterns problems in TypeScript