Skip to content

Commit

Permalink
Made resolvePathname handle absolute "to" much faster.
Browse files Browse the repository at this point in the history
Also decreased the size of the minzipped output a bit.
  • Loading branch information
StringEpsilon committed Aug 12, 2020
1 parent 8a3f4af commit f283185
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 31 deletions.
3 changes: 2 additions & 1 deletion src/utils/__tests__/resolvePathname.test.ts
Expand Up @@ -9,8 +9,9 @@ describe("resolvePathname", () => {
{ to: "/foo", from: "", result: "/foo" },
{ to: "/foo", from: "/bar", result: "/foo" },
{ to: "/foo", from: "/bar/baz", result: "/foo" },
{ to: "./foo", from: "/bar/baz", result: "/bar/foo" },
{ to: "/foo", from: "bar/baz", result: "/foo" },
// Relative shenanigangs:
{ to: "./foo", from: "/bar/baz", result: "/bar/foo" },
{ to: "..", from: "/bar/baz", result: "/" },
{ to: "..", from: "/bar/baz/", result: "/bar/" },
{ to: "../../..", from: "/bar/baz", result: "/" },
Expand Down
55 changes: 25 additions & 30 deletions src/utils/resolvePathname.ts
Expand Up @@ -21,48 +21,43 @@ export function resolvePathname(to: string, from: string = ""): string {
return to;
}
const toParts = to.split("/");
if(to[0] === "/"){ // Short-circuit absolute resolution
return toParts.filter(part => part !== "..").join("/");
}

let resultParts = from.split("/");
const fromRelative = from[0] !== "/";
let stackPosition = resultParts.length - 1;

if (to[0] !== "/") {
let push = false;
let reachedRoot = false;
for (let i = 0; i < toParts.length; i++) {
if (toParts[i] === "..") {
if (stackPosition > 0 && !reachedRoot) {
resultParts.pop();
stackPosition--;
resultParts[stackPosition] = "";
} else if (fromRelative) {
// if "from" is absolute, don't attempt to navigate back from root.
reachedRoot = true;
resultParts.unshift("..");
stackPosition++;
}
} else if (toParts[i] === ".") {
let push = false;
let reachedRoot = false;
for (let i = 0; i < toParts.length; i++) {
if (toParts[i] === "..") {
if (stackPosition > 0 && !reachedRoot) {
resultParts.pop();
stackPosition--;
resultParts[stackPosition] = "";
} else {
if (push) {
resultParts.push(toParts[i]);
stackPosition++;
} else {
resultParts[stackPosition] = toParts[i];
push = true;
}
} else if (fromRelative) {
// if "from" is absolute, don't attempt to navigate back from root.
reachedRoot = true;
resultParts.unshift("..");
stackPosition++;
}
}
} else {
resultParts = [];
for (let i = 0; i < toParts.length; i++) {
if (toParts[i] !== "..") {
} else if (toParts[i] === ".") {
resultParts[stackPosition] = "";
} else {
if (push) {
resultParts.push(toParts[i]);
stackPosition++;
} else {
resultParts[stackPosition] = toParts[i];
push = true;
}
}
}
let result = resultParts.join("/");
if (!fromRelative && result[0] !== "/") {
result = "/" + result;
return "/" + result;
}
return result;
}

0 comments on commit f283185

Please sign in to comment.