-
Notifications
You must be signed in to change notification settings - Fork 0
/
collect.ts
3479 lines (2945 loc) · 109 KB
/
collect.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { AnomalyDetectionOptions, AsyncCallback, CacheEntry, ClusterResult, Collection, CollectionMetrics, CollectionOperations, CompareFunction, ConditionalCallback, KeySelector, KMeansOptions, KMeansResult, LazyCollectionOperations, MovingAverageOptions, PaginationResult, PluckedCluster, PluckedData, RecordMerge, RegressionResult, SerializationOptions, StandardDeviationResult, TimeSeriesOptions, TimeSeriesPoint, ValidationResult, ValidationRule, ValidationSchema } from './types'
import process from 'node:process'
import { createLazyOperations } from './lazy'
import { calculateFuzzyScore, getNextTimestamp, isSameDay, validateCoordinates } from './utils'
/**
* Creates a new collection with optimized performance
* @param items - Array of items or iterable
*/
export function collect<T>(items: T[] | Iterable<T>): CollectionOperations<T> {
// Handle empty array case explicitly
if (Array.isArray(items) && items.length === 0) {
return createCollectionOperations({
items: [] as any[],
length: 0,
})
}
const array = Array.isArray(items) ? items : Array.from(items)
return createCollectionOperations({
items: array,
length: array.length,
})
}
/**
* @internal
*/
function createCollectionOperations<T>(collection: Collection<T>): CollectionOperations<T> {
// const versionStore: VersionStore<T> = {
// currentVersion: 0,
// snapshots: new Map(),
// changes: [],
// }
return {
...collection,
all() {
return [...collection.items]
},
average(key?: keyof T) {
return this.avg(key)
},
collapse<U>(): CollectionOperations<U> {
return collect(collection.items.flat() as U[])
},
combine<U>(values: U[]): CollectionOperations<Record<string, U | undefined>> {
const result: Record<string, U | undefined> = {}
collection.items.forEach((key, index) => {
result[String(key)] = values[index]
})
return collect([result]) as any
},
contains(keyOrItem: T | keyof T | undefined, value?: any): boolean {
if (arguments.length === 1) {
if (keyOrItem === undefined)
return false
return collection.items.includes(keyOrItem as T)
}
return collection.items.some(item => item[keyOrItem as keyof T] === value)
},
containsOneItem() {
return collection.length === 1
},
containsAll<K extends keyof T>(
itemsOrKey: Array<T | undefined> | K,
values?: Array<T[K] | undefined>,
): boolean {
if (arguments.length === 1) {
// Check direct items
const items = itemsOrKey as Array<T | undefined>
return items.every(item =>
item === undefined
? collection.items.includes(undefined as T)
: collection.items.includes(item),
)
}
// Check by key/values
const key = itemsOrKey as K
return (values || []).every(value =>
collection.items.some(item => item[key] === value),
)
},
countBy<K extends keyof T | string | number>(
keyOrCallback: K | ((item: T) => K extends keyof T ? T[K] : string | number),
): Map<any, number> {
const counts = new Map<any, number>()
for (const item of collection.items) {
const value = typeof keyOrCallback === 'function'
? (keyOrCallback as (item: T) => string | number)(item)
: item[keyOrCallback as keyof T]
counts.set(value, (counts.get(value) || 0) + 1)
}
return counts
},
diffAssoc(other: T[] | CollectionOperations<T>): CollectionOperations<T> {
const otherItems = Array.isArray(other) ? other : other.items
return collect(
collection.items.filter((item, index) =>
otherItems[index] === undefined || JSON.stringify(item) !== JSON.stringify(otherItems[index]),
),
)
},
diffKeys<K extends keyof T>(other: Record<K, T[K]>[]) {
return collect(
collection.items.filter(item =>
!other.some(otherItem =>
Object.keys(item as any).every(key =>
key in otherItem,
),
),
),
)
},
diffUsing(other: T[], callback: (a: T, b: T) => number) {
return collect(
collection.items.filter(item =>
!other.some(otherItem => callback(item, otherItem) === 0),
),
)
},
doesntContain(keyOrItem: keyof T | T, value?: any): boolean {
if (arguments.length === 1) {
return !collection.items.includes(keyOrItem as T)
}
return !collection.items.some(item =>
item[keyOrItem as keyof T] === value,
)
},
duplicates<K extends keyof T>(key?: K) {
const counts = new Map<any, number>()
const items = collection.items
items.forEach((item) => {
const value = key ? item[key] : item
counts.set(value, (counts.get(value) || 0) + 1)
})
return collect(
items.filter((item) => {
const value = key ? item[key] : item
return counts.get(value)! > 1
}),
)
},
each(callback: (item: T) => void): CollectionOperations<T> {
collection.items.forEach(callback)
return this
},
eachSpread(callback: (...args: any[]) => void): CollectionOperations<T> {
collection.items.forEach((item) => {
callback(...(Array.isArray(item) ? item : [item]))
})
return this
},
except<K extends keyof T>(...keys: K[]): CollectionOperations<Omit<T, K>> {
return collect(
collection.items.map((item) => {
const result = { ...item }
keys.forEach(key => delete result[key])
return result
}),
) as unknown as CollectionOperations<Omit<T, K>>
},
firstOrFail() {
const item = this.first()
if (!item)
throw new Error('Item not found.')
return item
},
firstWhere<K extends keyof T>(key: K, value: T[K]) {
return collection.items.find(item => item[key] === value)
},
flatten(depth = Infinity) {
const flat = (arr: any[], d: number): any[] => {
return d > 0
? arr.reduce((acc, val) =>
acc.concat(Array.isArray(val) ? flat(val, d - 1) : val), [])
: arr.slice()
}
return collect(flat(collection.items, depth))
},
flip<R extends Record<string | number, string | number> = {
[K in Extract<keyof T, string | number> as T[K] extends string | number ? T[K] : never]: K
}>(): CollectionOperations<R> {
// Handle empty collection
if (this.items.length === 0) {
return collect([] as R[])
}
const flipped: Record<string | number, string | number> = {}
// Type guard to ensure item is an object with string or number values
function isFlippable(item: any): item is Record<string, string | number> {
if (typeof item !== 'object' || item === null)
return false
return Object.values(item).every(
value => typeof value === 'string' || typeof value === 'number',
)
}
this.items.forEach((item) => {
if (isFlippable(item)) {
Object.entries(item).forEach(([key, value]) => {
flipped[value] = key
})
}
// If item is not flippable, ignore or handle as needed
})
// Return the flipped object as a single-item collection
return collect([flipped] as R[])
},
forget<K extends keyof T>(key: K): CollectionOperations<Omit<T, K>> {
return collect(
collection.items.map((item) => {
const result = { ...item }
delete result[key]
return result
}),
) as unknown as CollectionOperations<Omit<T, K>>
},
get<K extends keyof T>(key: K, defaultValue?: T[K]): T[K] | undefined {
const item = collection.items[0]
return item ? (item[key] !== undefined ? item[key] : defaultValue) : defaultValue
},
has<K extends keyof T>(key: K): boolean {
return collection.items.some(item => key in (item as Record<string, unknown>))
},
keyBy<K extends keyof T>(key: K) {
return new Map(
collection.items.map(item => [item[key], item]),
)
},
macro<Args extends any[]>(
name: string,
callback: (this: CollectionOperations<T>, ...args: Args) => CollectionOperations<any>,
): void {
Object.defineProperty(this, name, {
value(this: CollectionOperations<T>, ...args: Args) {
return callback.apply(this, args)
},
enumerable: false,
configurable: true,
writable: true,
})
},
make<U>(items: U[]) {
return collect(items)
},
mapInto<U extends Record<string, any>>(constructor: new () => U): CollectionOperations<U> {
return collect(
collection.items.map(item => Object.assign(new constructor(), item)),
) as unknown as CollectionOperations<U>
},
mapToDictionary<K extends string | number | symbol, V>(
callback: (item: T) => [K, V],
): Map<K, V> {
const map = new Map<K, V>()
collection.items.forEach((item) => {
const [key, value] = callback(item)
map.set(key, value)
})
return map
},
mapWithKeys<K extends string | number | symbol, V>(
callback: (item: T) => [K, V],
): Map<K, V> {
const map = new Map<K, V>()
collection.items.forEach((item) => {
const [key, value] = callback(item)
map.set(key, value)
})
return map
},
merge<U extends T>(other: U[] | CollectionOperations<U>): CollectionOperations<T | U> {
const otherItems = Array.isArray(other) ? other : other.items
return collect<T | U>([...collection.items, ...otherItems])
},
mergeRecursive<U>(other: U[] | CollectionOperations<U>): CollectionOperations<RecordMerge< T, U >> {
function mergeRecursiveHelper<A extends object, B extends object>(
target: A,
source: B,
): RecordMerge<A, B> {
if (source === undefined || source === null)
return target as RecordMerge<A, B>
if (Array.isArray(source))
return [...source] as RecordMerge<A, B>
if (typeof source !== 'object')
return source as RecordMerge<A, B>
const result: Record<string, any> = Array.isArray(target) ? [...target] : { ...target }
for (const key of Object.keys(source)) {
const sourceValue = (source as Record<string, any>)[key]
if (Array.isArray(sourceValue)) {
result[key] = [...sourceValue]
}
else if (sourceValue && typeof sourceValue === 'object') {
result[key] = key in result
? mergeRecursiveHelper(
result[key] as object,
sourceValue as object,
)
: { ...sourceValue }
}
else {
result[key] = sourceValue
}
}
return result as RecordMerge<A, B>
}
const otherItems = Array.isArray(other) ? other : other.items
const merged = collection.items.map((item, index) => {
return index < otherItems.length
? mergeRecursiveHelper(
item as object,
otherItems[index] as object,
)
: { ...item }
})
return collect(merged) as CollectionOperations<RecordMerge<T, U>>
},
only<K extends string>(...keys: K[]) {
return this.map((item: T) => {
const result = {} as { [P in K & keyof T]?: T[P] }
keys.forEach((key) => {
// Type guard to ensure item is an object before using 'in'
if (item && typeof item === 'object' && key in item) {
const typedKey = key as keyof T & K
result[typedKey] = item[typedKey]
}
})
return result
})
},
pad<U = T>(size: number, value: U): CollectionOperations<T | U> {
const result: Array<T | U> = collection.items.map(item => item as T | U)
const padSize = Math.abs(size)
while (result.length < padSize) {
size > 0 ? result.push(value) : result.unshift(value)
}
return collect<T | U>(result)
},
pop() {
return collection.items.pop()
},
prepend<U = T>(value: U): CollectionOperations<T | U> {
const result: Array<T | U> = [value, ...collection.items.map(item => item as T | U)]
return collect<T | U>(result)
},
pull<K extends keyof T>(key: K) {
const item = collection.items[0]
return item ? item[key] : undefined
},
push<U = T>(value: U): CollectionOperations<T | U> {
const result: Array<T | U> = [...collection.items.map(item => item as T | U), value]
return collect<T | U>(result)
},
put<K extends string, V>(key: K, value: V): CollectionOperations<any> {
return collect(
collection.items.map(item => ({ ...item, [key]: value })),
)
},
random(size?: number) {
const items = [...collection.items]
if (typeof size === 'undefined') {
const index = Math.floor(Math.random() * items.length)
return collect([items[index]])
}
const shuffled = items.sort(() => Math.random() - 0.5)
return collect(shuffled.slice(0, size))
},
reject(predicate: (item: T) => boolean) {
return this.filter(item => !predicate(item))
},
replace(items: T[]) {
return collect(items)
},
replaceRecursive<U>(items: U[]): CollectionOperations<U> {
function replaceDeep(target: any, source: any): any {
if (!source || typeof source !== 'object')
return source
if (Array.isArray(source)) {
return source.map((item, index) =>
replaceDeep(Array.isArray(target) ? target[index] : {}, item),
)
}
const result: any = {}
for (const key in source) {
result[key] = replaceDeep(target?.[key], source[key])
}
return result
}
return collect(replaceDeep(collection.items, items))
},
reverse() {
return collect([...collection.items].reverse())
},
shift(): T | undefined {
if (collection.length === 0)
return undefined
const value = collection.items[0]
collection.items.splice(0, 1)
return value
},
shuffle() {
return collect([...collection.items].sort(() => Math.random() - 0.5))
},
skipUntil(value: T | ((item: T) => boolean)): CollectionOperations<T> {
const predicate = typeof value === 'function'
? value as (item: T) => boolean
: (item: T) => item === value
const index = collection.items.findIndex(predicate)
return collect(
index === -1 ? [] : collection.items.slice(index),
) as CollectionOperations<T>
},
skipWhile(value: T | ((item: T) => boolean)) {
const predicate = typeof value === 'function'
? value as (item: T) => boolean
: (item: T) => item === value
let index = 0
while (index < collection.items.length && predicate(collection.items[index])) {
index++
}
return collect(collection.items.slice(index))
},
slice(start: number, length?: number) {
return collect(
length === undefined
? collection.items.slice(start)
: collection.items.slice(start, start + length),
)
},
sole() {
if (collection.length !== 1) {
throw new Error('Collection does not contain exactly one item.')
}
return collection.items[0]
},
sortDesc() {
return this.sort((a, b) => {
if (a < b)
return 1
if (a > b)
return -1
return 0
})
},
sortKeys() {
return collect(
collection.items.map((item) => {
const sorted: any = {}
Object.keys(item as object)
.sort()
.forEach((key) => {
sorted[key] = (item as any)[key]
})
return sorted as T
}),
)
},
sortKeysDesc() {
return collect(
collection.items.map((item) => {
const sorted: any = {}
Object.keys(item as object)
.sort((a, b) => b.localeCompare(a))
.forEach((key) => {
sorted[key] = (item as any)[key]
})
return sorted as T
}),
)
},
splice(start: number, deleteCount?: number, ...items: T[]): CollectionOperations<T> {
const copy = [...collection.items]
if (start > copy.length) {
return collect(copy)
}
if (deleteCount === undefined) {
copy.splice(start)
}
else {
copy.splice(start, deleteCount, ...items)
}
return collect(copy)
},
split(numberOfGroups: number) {
const result: T[][] = []
const itemsPerGroup = Math.ceil(collection.length / numberOfGroups)
for (let i = 0; i < collection.length; i += itemsPerGroup) {
result.push(collection.items.slice(i, i + itemsPerGroup))
}
return collect(result)
},
takeUntil(value: T | ((item: T) => boolean)) {
const predicate = typeof value === 'function'
? value as (item: T) => boolean
: (item: T) => item === value
const index = collection.items.findIndex(predicate)
return index === -1
? collect(collection.items)
: collect(collection.items.slice(0, index))
},
takeWhile(value: T | ((item: T) => boolean)) {
const predicate = typeof value === 'function'
? value as (item: T) => boolean
: (item: T) => item === value
let index = 0
while (index < collection.items.length && predicate(collection.items[index])) {
index++
}
return collect(collection.items.slice(0, index))
},
times<U>(count: number, callback: (index: number) => U) {
const items: U[] = []
for (let i = 0; i < count; i++) {
items.push(callback(i))
}
return collect(items)
},
undot() {
const result: Record<string, any> = {}
collection.items.forEach((item) => {
Object.entries(item as object).forEach(([key, value]) => {
key.split('.').reduce((acc: any, part, index, parts) => {
if (index === parts.length - 1) {
acc[part] = value
}
else {
acc[part] = acc[part] || {}
}
return acc[part]
}, result)
})
})
return collect([result])
},
unlessEmpty<U = T>(callback: (collection: CollectionOperations<T>) => CollectionOperations<U>): CollectionOperations<T | U> {
return this.isNotEmpty() ? callback(this) as CollectionOperations<T | U> : this as CollectionOperations<T | U>
},
unlessNotEmpty<U = T>(callback: (collection: CollectionOperations<T>) => CollectionOperations<U>): CollectionOperations<T | U> {
return this.isEmpty() ? callback(this) as CollectionOperations<T | U> : this as CollectionOperations<T | U>
},
unwrap<U>(value: U | U[] | CollectionOperations<U>): U extends any[] ? U : U[] {
if (value instanceof Object && 'items' in value) {
return (value as CollectionOperations<U>).toArray() as U extends any[] ? U : U[]
}
return (Array.isArray(value) ? value : [value]) as U extends any[] ? U : U[]
},
whenEmpty<U = T>(callback: (collection: CollectionOperations<T>) => CollectionOperations<U>): CollectionOperations<T | U> {
return this.isEmpty() ? callback(this) as CollectionOperations<T | U> : this as CollectionOperations<T | U>
},
whenNotEmpty<U = T>(callback: (collection: CollectionOperations<T>) => CollectionOperations<U>): CollectionOperations<T | U> {
return this.isNotEmpty() ? callback(this) as CollectionOperations<T | U> : this as CollectionOperations<T | U>
},
wrap<U>(value: U | U[]): CollectionOperations<U> {
if (Array.isArray(value)) {
return collect(value)
}
return collect([value])
},
zip<U>(array: U[]): CollectionOperations<[T, U | undefined]> {
return collect(
collection.items.map((item, index) => [item, array[index]] as [T, U | undefined]),
)
},
map<U>(callback: (item: T, index: number) => U): CollectionOperations<U> {
return collect(collection.items.map(callback))
},
filter(predicate: (item: T, index: number) => boolean): CollectionOperations<T> {
return collect(collection.items.filter(predicate))
},
reduce<U>(callback: (accumulator: U, current: T, index: number) => U, initialValue: U): U {
return collection.items.reduce(callback, initialValue)
},
flatMap<U>(callback: (item: T, index: number) => U[]): CollectionOperations<U> {
return collect(collection.items.flatMap(callback))
},
first: function <K extends keyof T>(key?: K): T | T[K] | undefined {
const item = collection.items[0]
if (arguments.length === 0) {
return item
}
return item ? item[key!] : undefined
} as {
(): T | undefined
<K extends keyof T>(key: K): T[K] | undefined
},
last: function <K extends keyof T>(key?: K): T | T[K] | undefined {
const item = collection.items[collection.length - 1]
if (arguments.length === 0) {
return item
}
return item ? item[key!] : undefined
} as {
(): T | undefined
<K extends keyof T>(key: K): T[K] | undefined
},
nth(index: number): T | undefined {
return collection.items[index]
},
take(count: number): CollectionOperations<T> {
return collect(collection.items.slice(0, count))
},
skip(count: number): CollectionOperations<T> {
return collect(collection.items.slice(count))
},
sum(key?: keyof T): number {
if (collection.length === 0)
return 0
return collection.items.reduce((sum, item) => {
const value = key ? Number(item[key]) : Number(item)
return sum + (Number.isNaN(value) ? 0 : value)
}, 0)
},
avg(key?: keyof T): number {
return collection.length ? this.sum(key) / collection.length : 0
},
median(key?: keyof T): number | undefined {
if (collection.length === 0)
return undefined
const values = key
? collection.items.map(item => Number(item[key])).sort((a, b) => a - b)
: collection.items.map(item => Number(item)).sort((a, b) => a - b)
const mid = Math.floor(values.length / 2)
return values.length % 2 === 0
? (values[mid - 1] + values[mid]) / 2
: values[mid]
},
mode(key?: keyof T): T | undefined {
if (collection.length === 0)
return undefined
const frequency = new Map<any, number>()
let maxFreq = 0
let mode: T | undefined
for (const item of collection.items) {
const value = key ? item[key] : item
const freq = (frequency.get(value) || 0) + 1
frequency.set(value, freq)
if (freq > maxFreq) {
maxFreq = freq
mode = item
}
}
return mode
},
min(key?: keyof T): T | undefined {
if (collection.length === 0)
return undefined
return collection.items.reduce((min, item) => {
const value = key ? item[key] : item
return value < (key ? min[key] : min) ? item : min
})
},
max(key?: keyof T): T | undefined {
if (collection.length === 0)
return undefined
return collection.items.reduce((max, item) => {
const value = key ? item[key] : item
return value > (key ? max[key] : max) ? item : max
})
},
chunk(size: number): CollectionOperations<T[]> {
if (size < 1)
throw new Error('Chunk size must be greater than 0')
const chunks: T[][] = []
for (let i = 0; i < collection.length; i += size) {
chunks.push(collection.items.slice(i, i + size))
}
return collect(chunks)
},
groupBy<K extends keyof T>(keyOrCallback: K | KeySelector<T>): Map<any, CollectionOperations<T>> {
const groups = new Map<any, T[]>()
for (const item of collection.items) {
const key = typeof keyOrCallback === 'function'
? keyOrCallback(item)
: item[keyOrCallback]
if (!groups.has(key))
groups.set(key, [])
groups.get(key)!.push(item)
}
return new Map(
Array.from(groups.entries()).map(
([key, items]) => [key, collect(items)],
),
)
},
partition(predicate: (item: T) => boolean): [CollectionOperations<T>, CollectionOperations<T>] {
const pass: T[] = []
const fail: T[] = []
for (const item of collection.items) {
if (predicate(item)) {
pass.push(item)
}
else {
fail.push(item)
}
}
return [collect(pass), collect(fail)]
},
where<K extends keyof T>(key: K, value: T[K]): CollectionOperations<T> {
return collect(collection.items.filter(item => item[key] === value))
},
whereIn<K extends keyof T>(key: K, values: T[K][]): CollectionOperations<T> {
const valueSet = new Set(values)
return collect(collection.items.filter(item => valueSet.has(item[key])))
},
whereNotIn<K extends keyof T>(key: K, values: T[K][]): CollectionOperations<T> {
const valueSet = new Set(values)
return collect(collection.items.filter(item => !valueSet.has(item[key])))
},
whereBetween<K extends keyof T>(key: K, min: T[K], max: T[K]): CollectionOperations<T> {
return collect(collection.items.filter((item) => {
const value = item[key]
return value >= min && value <= max
}))
},
whereNotBetween<K extends keyof T>(key: K, min: T[K], max: T[K]): CollectionOperations<T> {
return collect(collection.items.filter((item) => {
const value = item[key]
return value < min || value > max
}))
},
unique<K extends keyof T>(key?: K): CollectionOperations<T> {
if (!key)
return collect([...new Set(collection.items)])
const seen = new Set<T[K]>()
return collect(
collection.items.filter((item) => {
const value = item[key]
if (seen.has(value))
return false
seen.add(value)
return true
}),
)
},
when<U = T>(
condition: boolean | ConditionalCallback<T>,
callback: (collection: CollectionOperations<T>) => CollectionOperations<U>,
): CollectionOperations<U> {
const shouldRun = typeof condition === 'function' ? condition(this) : condition
return shouldRun ? callback(this) : this as unknown as CollectionOperations<U>
},
unless<U = T>(
condition: boolean | ConditionalCallback<T>,
callback: (collection: CollectionOperations<T>) => CollectionOperations<U>,
): CollectionOperations<U> {
const shouldRun = typeof condition === 'function' ? condition(this) : condition
return shouldRun ? this as unknown as CollectionOperations<U> : callback(this)
},
sort(compareFunction?: CompareFunction<T>): CollectionOperations<T> {
if (!compareFunction) {
const sorted = [...collection.items]
// Separate items by type
const nulls: T[] = []
const undefineds: T[] = []
const values: T[] = []
for (const item of sorted) {
if (item === null) {
nulls.push(item)
}
else if (item === undefined) {
undefineds.push(item)
}
else {
values.push(item)
}
}
// Sort regular values
values.sort((a: any, b: any) => {
if (typeof a === 'number' && typeof b === 'number') {
return a - b
}
return String(a).localeCompare(String(b))
})
// Combine in desired order: nulls, undefineds, sorted values
return collect([...nulls, ...undefineds, ...values])
}
return collect([...collection.items].sort(compareFunction))
},
sortBy<K extends keyof T>(key: K, direction: 'asc' | 'desc' = 'asc'): CollectionOperations<T> {
const sorted = [...collection.items]
if (sorted.length === 0) {
return collect(sorted)
}
// Check if any item has a defined value for the key
const hasDefinedValues = sorted.some(item =>
item?.[key] !== undefined && item[key] !== null,
)
// Return original order if no item has a defined value for the key
if (!hasDefinedValues) {
return collect(sorted)
}
return collect(sorted.sort((a, b) => {
const aVal = a?.[key]
const bVal = b?.[key]
// Handles undefined/null values
if (aVal === undefined || aVal === null) {
return direction === 'asc' ? -1 : 1
}
if (bVal === undefined || bVal === null) {
return direction === 'asc' ? 1 : -1
}
// Sort numbers numerically
if (typeof aVal === 'number' && typeof bVal === 'number') {
return direction === 'asc' ? aVal - bVal : bVal - aVal
}
// Sort everything else as strings
const comparison = String(aVal).localeCompare(String(bVal))
return direction === 'asc' ? comparison : -comparison
}))
},
sortByDesc<K extends keyof T>(key: K): CollectionOperations<T> {
return this.sortBy(key, 'desc')
},
pluck<K extends keyof T>(key: K): CollectionOperations<T[K]> {
return collect(collection.items.map(item => item[key]))
},
values(): CollectionOperations<T> {
return collect([...collection.items])
},
keys<K extends keyof T>(key: K): CollectionOperations<T[K]> {
return collect(Array.from(new Set(collection.items.map(item => item[key]))))
},
// setDiff(other: T[] | CollectionOperations<T>): CollectionOperations<T> {
// const otherSet = new Set(Array.isArray(other) ? other : other.items)
// return collect(collection.items.filter(item => !otherSet.has(item)))
// },
// get currentVersion(): number {
// return versionStore.currentVersion
// },
// async snapshot(): Promise<number> {
// const version = versionStore.currentVersion + 1
// versionStore.snapshots.set(version, {
// items: [...collection.items],
// timestamp: new Date(),
// })
// versionStore.currentVersion = version
// return version
// },
// hasVersion(version: number): boolean {
// return versionStore.snapshots.has(version)
// },
// getVersion(version: number): CollectionOperations<T> | null {
// const snapshot = versionStore.snapshots.get(version)
// if (!snapshot)
// return null
// return collect(snapshot.items)
// },
// diff(version1: number, version2: number): CollectionOperations<VersionInfo<T>> {
// // Ensure both versions exist
// const snapshot1 = versionStore.snapshots.get(version1)
// const snapshot2 = versionStore.snapshots.get(version2)