2
2
/* eslint-disable @typescript-eslint/no-explicit-any */
3
3
4
4
/**
5
- * Type that represents the partitioned properties from an object type T.
5
+ * Type that represents the partitioned properties from an object type T.
6
6
* For each selected property K from T, creates an array of that property's type.
7
7
* Also includes a 'rest' property containing an array of objects with all non-selected properties.
8
- *
9
8
* @template T - The source object type
10
9
* @template K - The keys to partition from T
11
10
* @example
@@ -34,11 +33,10 @@ type PartitionedArrayProperties<T, K extends keyof T> = {
34
33
/** The array of remaining properties not selected for partitioning */
35
34
rest : Array < Omit < T , K > > ;
36
35
} ;
37
-
36
+
38
37
/**
39
38
* Partitions an array of objects by separating specified properties into their own arrays
40
39
* while keeping the remaining properties grouped in a 'rest' array.
41
- *
42
40
* @template T - The type of objects in the input array
43
41
* @template K - The keys of properties to partition
44
42
* @param items - Array of objects to partition
@@ -50,10 +48,10 @@ type PartitionedArrayProperties<T, K extends keyof T> = {
50
48
* { id: 2, name: 'Jane', age: 30, city: 'LA' }
51
49
* ]
52
50
* const result = partitionObjectArray(items, ['id', 'name']);
53
- * // Returns: {
54
- * // id: [1, 2],
55
- * // name: ['John', 'Jane'],
56
- * // rest: [{age: 25, city: 'NY'}, {age: 30, city: 'LA'}]
51
+ * // Returns: {
52
+ * // id: [1, 2],
53
+ * // name: ['John', 'Jane'],
54
+ * // rest: [{age: 25, city: 'NY'}, {age: 30, city: 'LA'}]
57
55
* // }
58
56
*/
59
57
export const partitionObjectArray = < T extends object , K extends keyof T > (
@@ -62,22 +60,20 @@ type PartitionedArrayProperties<T, K extends keyof T> = {
62
60
) : PartitionedArrayProperties < T , K > =>
63
61
items . reduce ( ( acc , item ) => {
64
62
const result = { ...acc } as PartitionedArrayProperties < T , K > ;
65
-
63
+
66
64
properties . forEach ( ( prop ) => {
67
65
const currentArray = ( acc [ prop ] || [ ] ) as T [ K ] [ ] ;
68
66
result [ prop ] = [ ...currentArray , item [ prop ] ] as any ;
69
67
} ) ;
70
-
68
+
71
69
const restObject = { } as Omit < T , K > ;
72
70
Object . entries ( item ) . forEach ( ( [ key , value ] ) => {
73
71
if ( ! properties . includes ( key as K ) ) {
74
72
( restObject as any ) [ key ] = value ;
75
73
}
76
74
} ) ;
77
-
75
+
78
76
result . rest = [ ...( acc . rest || [ ] ) , restObject ] ;
79
-
77
+
80
78
return result ;
81
79
} , { } as PartitionedArrayProperties < T , K > ) ;
82
-
83
-
0 commit comments