From 976a7ab5e4be905384ec54b9483f7a2cfa6e642e Mon Sep 17 00:00:00 2001 From: SSHari Date: Sat, 14 Oct 2023 00:57:58 -0400 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=90=9B=20handle=20the=20array=20us?= =?UTF-8?q?e=20case=20first=20in=20the=20stableJson=20util?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/utilities/stableJson.ts | 9 +++++---- tests/stableJson.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/app/utilities/stableJson.ts b/app/utilities/stableJson.ts index 2e5d486e..a45dc5f3 100644 --- a/app/utilities/stableJson.ts +++ b/app/utilities/stableJson.ts @@ -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) => { @@ -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; for (const key of Object.keys(json)) { diff --git a/tests/stableJson.test.ts b/tests/stableJson.test.ts index 7190264e..a38bc308 100644 --- a/tests/stableJson.test.ts +++ b/tests/stableJson.test.ts @@ -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 + ] + ] +}" +`); +});