Total Complexity | 15 |
Complexity/F | 5 |
Lines of Code | 50 |
Function Count | 3 |
Duplicated Lines | 0 |
Ratio | 0 % |
Coverage | 100% |
Changes | 0 |
1 | /** |
||
2 | * Enumeration of data types. |
||
3 | * @enum {string} |
||
4 | */ |
||
5 | 1 | enum DataType { |
|
6 | 1 | OBJECT = 'object', |
|
7 | 1 | ARRAY = 'array', |
|
8 | 1 | PRIMITIVE = 'primitive' |
|
9 | } |
||
10 | |||
11 | /** |
||
12 | * Function to determine the data type of the provided data. |
||
13 | * @param {unknown} data - The data to be checked. |
||
14 | * @returns {DataType} The DataType value corresponding to the data's type. |
||
15 | */ |
||
16 | function getType(data: unknown): DataType { |
||
17 | 47 | if (Array.isArray(data)) return DataType.ARRAY; |
|
18 | 43 | if (data !== null && typeof data === 'object') return DataType.OBJECT; |
|
19 | 29 | return DataType.PRIMITIVE; |
|
20 | } |
||
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 |