Passed
Push — main ( 48e127...411ece )
by Yuri
01:52
created

index.ts ➔ sort   B

Complexity

Conditions 6

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 28
ccs 13
cts 13
cp 1
rs 8.5166
c 0
b 0
f 0
cc 6
crap 6
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