Skip to content

Commit

Permalink
Merge pull request #223 from denisw/fix/sort-nested-property
Browse files Browse the repository at this point in the history
Fix sorting error in case of nested trailing comma
  • Loading branch information
aiday-mar authored Mar 4, 2024
2 parents bbba2d5 + 87b872e commit e140c73
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
2 changes: 1 addition & 1 deletion src/test/sort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ suite('Sort JSON', () => {
'"hobbies" : ["volleyball","drawing","hiking"],',
'"friends" : {',
'"Marc" : {"hobbies" : ["kayaking", "mountaineering"],',
'"age" : 35},',
'"age" : 35,},',
'"Leila" : {"hobbies" : ["watching movies",',
'"reading books"], "age" : 32}}}'
].join('\n');
Expand Down
21 changes: 11 additions & 10 deletions src/utils/sort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,16 +222,17 @@ function findJsoncPropertyTree(formattedDocument: TextDocument) {
endLineNumber = scanner.getTokenStartLine();
currentContainerStack.pop();

// If we are not inside of an empty object and current property end line number has not yet been defined, define it
if (lastNonTriviaNonCommentToken !== SyntaxKind.OpenBraceToken
&& currentProperty!.endLineNumber === undefined) {

currentProperty!.endLineNumber = endLineNumber - 1;
// The current property is also the last property
currentProperty!.lastProperty = true;
// The last property of an object is associated with the line and index of where to add the comma, in case after sorting, it is no longer the last property
currentProperty!.lineWhereToAddComma = lineOfLastNonTriviaNonCommentToken;
currentProperty!.indexWhereToAddComa = endIndexOfLastNonTriviaNonCommentToken;
// If we are not inside of an empty object
if (lastNonTriviaNonCommentToken !== SyntaxKind.OpenBraceToken) {
// If current property end line number has not yet been defined, define it
if (currentProperty!.endLineNumber === undefined) {
currentProperty!.endLineNumber = endLineNumber - 1;
// The current property is also the last property
currentProperty!.lastProperty = true;
// The last property of an object is associated with the line and index of where to add the comma, in case after sorting, it is no longer the last property
currentProperty!.lineWhereToAddComma = lineOfLastNonTriviaNonCommentToken;
currentProperty!.indexWhereToAddComa = endIndexOfLastNonTriviaNonCommentToken;
}
lastProperty = currentProperty;
currentProperty = currentProperty ? currentProperty.parent : undefined;
currentTree = currentProperty;
Expand Down

0 comments on commit e140c73

Please sign in to comment.