Skip to content

Commit

Permalink
fix(calculateNearestUniquePath): ensures unique paths (#311)
Browse files Browse the repository at this point in the history
* fix(calculateNearestUniquePath): ensures unique paths

* Update stringUtils.test.ts and stringUtils.ts
  • Loading branch information
danilowoz authored Jan 20, 2022
1 parent eb9c269 commit a337269
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
6 changes: 6 additions & 0 deletions sandpack-react/src/utils/stringUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ describe(calculateNearestUniquePath, () => {
).toBe("test/something/index.js");
});

it("keeps path when same level and same name", () => {
expect(
calculateNearestUniquePath("/other/index.js", ["/test/index.js"])
).toBe("other/index.js");
});

it("adds a leading `..` when other open paths have the same fileName, but different paths", () => {
expect(
calculateNearestUniquePath("/test/something/index.js", [
Expand Down
10 changes: 7 additions & 3 deletions sandpack-react/src/utils/stringUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ export const calculateNearestUniquePath = (
currentPath: string,
otherPaths: string[]
): string => {
const currentPathParts = currentPath.split("/");
const currentPathParts = (
currentPath[0] === "/" ? currentPath.slice(1) : currentPath
).split("/");
const resultPathParts: string[] = [];

// If path is on root, there are no parts to loop through
Expand All @@ -20,17 +22,19 @@ export const calculateNearestUniquePath = (
const otherPathParts = otherPaths[fileIndex].split("/");
for (
let partsFromEnd = 1;
partsFromEnd < currentPathParts.length;
partsFromEnd <= currentPathParts.length;
partsFromEnd++
) {
const currentPathPart =
currentPathParts[currentPathParts.length - partsFromEnd];
const otherPathPart =
otherPathParts[otherPathParts.length - partsFromEnd];

// If this part hasn't been added to the result path, we add it here
if (resultPathParts.length < partsFromEnd) {
resultPathParts.unshift(currentPathPart);
}

// If this part is different between the current path and other path we break
// as from this moment the current path is unique compared to this other path
if (currentPathPart !== otherPathPart) {
Expand All @@ -41,7 +45,7 @@ export const calculateNearestUniquePath = (
}

// Add `..` if this is a relative path
if (resultPathParts.length + 1 < currentPathParts.length) {
if (resultPathParts.length < currentPathParts.length) {
resultPathParts.unshift("..");
}

Expand Down

0 comments on commit a337269

Please sign in to comment.