Skip to content

Commit

Permalink
Merge pull request #175 from SSHari/patch-174
Browse files Browse the repository at this point in the history
fix: 🐛 handle the array use case first in the stableJson util
  • Loading branch information
matt-aitken committed Oct 17, 2023
2 parents 9d63124 + 976a7ab commit 57361c6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
9 changes: 5 additions & 4 deletions app/utilities/stableJson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ export function stableJson(json: unknown, keyOrder: string[] = []): unknown {
const keyOrder = Object.keys(json[0]);
return json.map((c) => stableJson(c, keyOrder));
}

if (Array.isArray(json)) {
return json.map((c) => stableJson(c));
}

if (typeof json === "object" && json !== null && keyOrder.length > 0) {
const keys = Object.keys(json);
const sortedKeys = keys.sort((a, b) => {
Expand All @@ -26,10 +31,6 @@ export function stableJson(json: unknown, keyOrder: string[] = []): unknown {
return result;
}

if (Array.isArray(json)) {
return json.map((c) => stableJson(c));
}

if (typeof json === "object" && json !== null) {
const result = {} as Record<string, unknown>;
for (const key of Object.keys(json)) {
Expand Down
22 changes: 22 additions & 0 deletions tests/stableJson.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,25 @@ test("It should order object keys in a similar order as the first object in an a
}"
`);
});

test("It should not convert an array to an object in nested arrays", () => {
const json = {
data: [
[1],
[2]
],
};

expect(JSON.stringify(stableJson(json), null, 2)).toMatchInlineSnapshot(`
"{
\\"data\\": [
[
1
],
[
2
]
]
}"
`);
});

0 comments on commit 57361c6

Please sign in to comment.