Skip to content

Commit

Permalink
fix: 🐛 handle the array use case first in the stableJson util
Browse files Browse the repository at this point in the history
  • Loading branch information
SSHari committed Oct 14, 2023
1 parent 9d63124 commit 976a7ab
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 976a7ab

Please sign in to comment.