Conditions | 6 |
Total Lines | 28 |
Code Lines | 19 |
Lines | 0 |
Ratio | 0 % |
Tests | 13 |
CRAP Score | 6 |
Changes | 0 |
1 | /** |
||
21 | |||
22 | /** |
||
23 | * Function to sort JSON data. |
||
24 | * @param {unknown} data - The data to be sorted. |
||
25 | * @param {boolean} [asc=true] - Whether to sort in ascending order. |
||
26 | * @returns {unknown} The sorted data. |
||
27 | */ |
||
28 | 1 | export function sort(data: unknown, asc: boolean = true): unknown { |
|
29 | 20 | const type = getType(data); |
|
30 | |||
31 | 20 | if (type === DataType.ARRAY) { |
|
32 | 3 | return (data as unknown[]).map(item => |
|
33 | 7 | getType(item) !== DataType.PRIMITIVE ? sort(item, asc) : item |
|
34 | ); |
||
35 | } |
||
36 | |||
37 | 17 | if (type === DataType.OBJECT) { |
|
38 | 9 | const sortedKeys = Object.keys(data as object).sort(); |
|
39 | 9 | if (!asc) sortedKeys.reverse(); |
|
40 | |||
41 | 9 | return sortedKeys.reduce((result: Record<string, unknown>, key) => { |
|
42 | 20 | const value = (data as Record<string, unknown>)[key]; |
|
43 | 20 | result[key] = getType(value) !== DataType.PRIMITIVE ? sort(value, asc) : value; |
|
44 | 20 | return result; |
|
45 | }, {}); |
||
46 | } |
||
47 | |||
48 | 8 | return data; |
|
49 | } |
||
50 |