Passed
Push — main ( 411ece...81a98c )
by Yuri
01:09 queued 15s
created

index.ts ➔ sort   A

Complexity

Conditions 5

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 16
dl 0
loc 24
ccs 11
cts 11
cp 1
crap 5
rs 9.1333
c 0
b 0
f 0
1
/**
2
 * Function to sort JSON data.
3
 * @param {unknown} data - The data to be sorted.
4
 * @param {boolean} [asc=true] - Whether to sort in ascending order.
5
 * @returns {unknown} The sorted data.
6
 */
7 1
export function sort(data: unknown, asc: boolean = true): unknown {
8 105
  if (!data || typeof data !== 'object') {
9 61
    return data;
10
  }
11
12 44
  if (Array.isArray(data)) {
13 27
    return data.map(item => sort(item, asc));
14
  }
15
16 35
  if (isNonSortableObject(data)) {
17 11
    return data;
18
  }
19
20 24
  const sortedEntries = Object.entries(data as Record<string, unknown>)
21 52
    .sort(([a], [b]) => asc ? a.localeCompare(b) : b.localeCompare(a));
22
  
23 24
  return Object.fromEntries(
24 60
    sortedEntries.map(([key, value]) => [key, sort(value, asc)])
25
  );
26
}
27
28
function isNonSortableObject(obj: object): boolean {
29 35
  return (
30
    obj instanceof Date ||
31
    obj instanceof RegExp ||
32
    obj instanceof Function ||
33
    obj instanceof Error ||
34
    obj instanceof Map ||
35
    obj instanceof Set ||
36
    obj instanceof WeakMap ||
37
    obj instanceof WeakSet ||
38
    obj instanceof Promise ||
39
    Symbol.iterator in Object(obj)
40
  );
41
}
42