(json: unknown, keyOrder: string[] = [])
| 1 | export function stableJson(json: unknown, keyOrder: string[] = []): unknown { |
| 2 | if ( |
| 3 | Array.isArray(json) && |
| 4 | json.length > 0 && |
| 5 | json.every((c) => typeof c === "object" && c !== null) |
| 6 | ) { |
| 7 | const keyOrder = Object.keys(json[0]); |
| 8 | return json.map((c) => stableJson(c, keyOrder)); |
| 9 | } |
| 10 | |
| 11 | if (Array.isArray(json)) { |
| 12 | return json.map((c) => stableJson(c)); |
| 13 | } |
| 14 | |
| 15 | if (typeof json === "object" && json !== null && keyOrder.length > 0) { |
| 16 | const keys = Object.keys(json); |
| 17 | const sortedKeys = keys.sort((a, b) => { |
| 18 | const aIndex = keyOrder.indexOf(a); |
| 19 | const bIndex = keyOrder.indexOf(b); |
| 20 | |
| 21 | if (aIndex === -1 || bIndex === -1) { |
| 22 | return 0; |
| 23 | } |
| 24 | |
| 25 | return aIndex - bIndex; |
| 26 | }); |
| 27 | const result = {} as Record<string, unknown>; |
| 28 | for (const key of sortedKeys) { |
| 29 | result[key] = stableJson((json as Record<string, unknown>)[key]); |
| 30 | } |
| 31 | return result; |
| 32 | } |
| 33 | |
| 34 | if (typeof json === "object" && json !== null) { |
| 35 | const result = {} as Record<string, unknown>; |
| 36 | for (const key of Object.keys(json)) { |
| 37 | result[key] = stableJson((json as Record<string, unknown>)[key]); |
| 38 | } |
| 39 | return result; |
| 40 | } |
| 41 | |
| 42 | return json; |
| 43 | } |
no outgoing calls
no test coverage detected