-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
kt_iterable.dart
1787 lines (1639 loc) · 63.6 KB
/
kt_iterable.dart
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 "dart:math" as math;
import "package:kt_dart/collection.dart";
import "package:kt_dart/src/util/errors.dart";
/// Classes that inherit from this interface can be represented as a sequence of elements that can
/// be iterated over.
/// @param T the type of element being iterated over. The iterator is covariant on its element type.
abstract class KtIterable<T> {
/// Access to a [Iterable] to be used in for-loops
Iterable<T> get iter;
/// Returns an iterator over the elements of this object.
KtIterator<T> iterator();
}
extension KtComparableIterableExtension<T extends Comparable<T>>
on KtIterable<T> {
/// Returns the largest element or `null` if there are no elements.
@Deprecated("use maxOrNull")
T? max() => maxOrNull();
/// Returns the largest element or `null` if there are no elements.
T? maxOrNull() {
final i = iterator();
if (!iterator().hasNext()) return null;
T max = i.next();
while (i.hasNext()) {
final T e = i.next();
if (Comparable.compare(max, e) < 0) {
max = e;
}
}
return max;
}
/// Returns the smallest element or `null` if there are no elements.
@Deprecated("use minOrNull")
T? min() => minOrNull();
/// Returns the smallest element or `null` if there are no elements.
T? minOrNull() {
final i = iterator();
if (!iterator().hasNext()) return null;
T min = i.next();
while (i.hasNext()) {
final T e = i.next();
if (Comparable.compare(min, e) > 0) {
min = e;
}
}
return min;
}
}
extension KtNumIterableExtension<T extends num> on KtIterable<T> {
/// Returns the largest element or `null` if there are no elements.
@Deprecated("use maxOrNull")
T? max() => maxOrNull();
/// Returns the largest element or `null` if there are no elements.
T? maxOrNull() {
final i = iterator();
if (!iterator().hasNext()) return null;
T max = i.next();
if (max.isNaN) return max;
while (i.hasNext()) {
final T e = i.next();
if (e.isNaN) return e;
if (max < e) {
max = e;
}
}
return max;
}
/// Returns the smallest element or `null` if there are no elements.
@Deprecated("use minOrNull")
T? min() => minOrNull();
/// Returns the smallest element or `null` if there are no elements.
T? minOrNull() {
final i = iterator();
if (!iterator().hasNext()) return null;
T min = i.next();
if (min.isNaN) return min;
while (i.hasNext()) {
final T e = i.next();
if (e.isNaN) return e;
if (min > e) {
min = e;
}
}
return min;
}
/// Returns the average or `null` if there are no elements.
double average() {
var count = 0;
num sum = 0;
final i = iterator();
if (!iterator().hasNext()) return double.nan;
while (i.hasNext()) {
final next = i.next();
// nan values are ignored
if (!next.isNaN) {
sum += next;
count++;
}
}
return sum / count;
}
}
extension KtIntIterableExtension on KtIterable<int> {
/// Returns the sum of all elements in the collection.
int sum() {
int sum = 0;
for (final element in iter) {
sum += element;
}
return sum;
}
}
extension KtDoubleIterableExtension on KtIterable<double> {
/// Returns the sum of all elements in the collection.
double sum() {
double sum = 0.0;
for (final element in iter) {
sum += element;
}
return sum;
}
}
extension KtIterableExtensions<T> on KtIterable<T> {
/// Returns a dart:core [Iterable]
///
/// This method can be used to interop between the dart:collection and the
/// kt.dart world.
Iterable<T> get dart => iter;
/// Returns `true` if all elements match the given [predicate].
bool all(bool Function(T element) predicate) {
if (this is KtCollection && (this as KtCollection).isEmpty()) return true;
for (final element in iter) {
if (!predicate(element)) {
return false;
}
}
return true;
}
/// Returns `true` if at least one element matches the given [predicate].
///
/// Returns `true` if collection has at least one element when no [predicate] is provided
bool any([bool Function(T element)? predicate]) {
if (predicate == null) {
if (this is KtCollection) return !(this as KtCollection).isEmpty();
return iterator().hasNext();
}
if (this is KtCollection && (this as KtCollection).isEmpty()) return false;
for (final element in iter) {
if (predicate(element)) return true;
}
return false;
}
/// Returns this collection as an [Iterable].
KtIterable<T> asIterable() => this;
/// Returns a [Map] containing key-value pairs provided by [transform] function
/// applied to elements of the given collection.
///
/// If any of two pairs would have the same key the last one gets added to the map.
///
/// The returned map preserves the entry iteration order of the original collection.
KtMap<K, V> associate<K, V>(KtPair<K, V> Function(T) transform) {
final map = associateTo(linkedMapFrom<K, V>(), transform);
// TODO ping dort-lang/sdk team to check type bug
// When in single line: type 'DartLinkedHashMap<String, String>' is not a subtype of type 'Null'
return map;
}
/// Returns a [Map] containing the elements from the given collection indexed by the key
/// returned from [keySelector] function applied to each element.
///
/// If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
///
/// The returned map preserves the entry iteration order of the original collection.
KtMap<K, T> associateBy<K>(K Function(T) keySelector) {
return associateByTo<K, T, KtMutableMap<K, T>>(
linkedMapFrom<K, T>(), keySelector);
}
/// Returns a [Map] containing the elements from the given collection indexed by the key
/// returned from [keySelector] function applied to each element. The element can be transformed with [valueTransform].
///
/// If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
///
/// The returned map preserves the entry iteration order of the original collection.
KtMap<K, V> associateByTransform<K, V>(
K Function(T) keySelector, V Function(T) valueTransform) {
final map =
associateByTo(linkedMapFrom<K, V>(), keySelector, valueTransform);
// TODO ping dort-lang/sdk team to check type bug
// When in single line: type 'DartLinkedHashMap<int, String>' is not a subtype of type 'Null'
return map;
}
/// Populates and returns the [destination] mutable map with key-value pairs,
/// where key is provided by the [keySelector] function and
/// and value is provided by the [valueTransform] function applied to elements of the given collection.
///
/// If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
M associateByTo<K, V, M extends KtMutableMap<K, V>>(
M destination, K Function(T) keySelector,
[V Function(T)? valueTransform]) {
for (final element in iter) {
final key = keySelector(element);
final V value =
valueTransform == null ? element as V : valueTransform(element);
destination.put(key, value);
}
return destination;
}
/// Populates and returns the [destination] mutable map with key-value pairs
/// provided by [transform] function applied to each element of the given collection.
///
/// If any of two pairs would have the same key the last one gets added to the map.
M associateTo<K, V, M extends KtMutableMap<K, V>>(
M destination, KtPair<K, V> Function(T) transform) {
for (final element in iter) {
final pair = transform(element);
destination.put(pair.first, pair.second);
}
return destination;
}
/// Returns a [Map] where keys are elements from the given collection and values are
/// produced by the [valueSelector] function applied to each element.
///
/// If any two elements are equal, the last one gets added to the map.
///
/// The returned map preserves the entry iteration order of the original collection.
KtMap<T, V> associateWith<V>(V Function(T) valueSelector) {
final associated = associateWithTo(linkedMapFrom<T, V>(), valueSelector);
// TODO ping dort-lang/sdk team to check type bug
// When in single line: type "DartMutableList<String>' is not a subtype of type 'Null"
return associated;
}
/// Populates and returns the [destination] mutable map with key-value pairs for each element of the given collection,
/// where key is the element itself and value is provided by the [valueSelector] function applied to that key.
///
/// If any two elements are equal, the last one overwrites the former value in the map.
///
/// [destination] is not type checked by the compiler due to https://github.com/dart-lang/sdk/issues/35518,
/// but will be checked at runtime.
/// [M] actually is expected to be `M extends KtMutableMap<T, V>`
// TODO Change to `M extends KtMutableMap<T, V>` once https://github.com/dart-lang/sdk/issues/35518 has been fixed
M associateWithTo<V, M extends KtMutableMap<dynamic, dynamic>>(
M destination, V Function(T) valueSelector) {
assert(() {
if (destination is! KtMutableMap<T, V> && mutableMapFrom<T, V>() is! M) {
throw ArgumentError(
"associateWithTo destination has wrong type parameters."
"\nExpected: KtMutableMap<$T, $V>, Actual: ${destination.runtimeType}"
"\ndestination (${destination.runtimeType}) items aren't subtype of "
"$runtimeType items. Items can't be copied to destination."
"\n\n$kBug35518GenericTypeError");
}
return true;
}());
for (final element in iter) {
destination.put(element, valueSelector(element));
}
return destination;
}
/// Returns an average value produced by [selector] function applied to each element in the collection.
double averageBy(num Function(T) selector) {
num sum = 0.0;
var count = 0;
for (final element in iter) {
final value = selector(element);
// nan values are ignored
if (!value.isNaN) {
sum += value;
count++;
}
}
if (count == 0) {
return double.nan;
}
return sum / count;
}
/// Provides a view of this [KtIterable] as an iterable of [R] instances.
///
/// If this [KtIterable] only contains instances of [R], all operations will work correctly.
/// If any operation tries to access an element that is not an instance of [R], the access will throw a [TypeError] instead.
///
/// When the returned [KtIterable] creates a new object that depends on the type [R], e.g., from [toList], it will have exactly the type [R].
KtIterable<R> cast<R>() => _CastKtIterable<T, R>(this);
/// Splits this collection into a list of lists each not exceeding the given [size].
///
/// The last list in the resulting list may have less elements than the given [size].
///
/// @param [size] the number of elements to take in each list, must be positive and can be greater than the number of elements in this collection.
KtList<KtList<T>> chunked(int size) {
return windowed(size, step: size, partialWindows: true);
}
/// Splits this collection into several lists each not exceeding the given [size]
/// and applies the given [transform] function to an each.
///
/// @return list of results of the [transform] applied to an each list.
///
/// Note that the list passed to the [transform] function is ephemeral and is valid only inside that function.
/// You should not store it or allow it to escape in some way, unless you made a snapshot of it.
/// The last list may have less elements than the given [size].
///
/// @param [size] the number of elements to take in each list, must be positive and can be greater than the number of elements in this collection.
///
KtList<R> chunkedTransform<R>(int size, R Function(KtList<T>) transform) {
return windowedTransform(size, transform, step: size, partialWindows: true);
}
/// Returns `true` if [element] is found in the collection.
bool contains(T element) {
if (this is KtCollection) return (this as KtCollection).contains(element);
return indexOf(element) >= 0;
}
/// Returns the number of elements matching the given [predicate] or the number of elements when `predicate = null`.
int count([bool Function(T)? predicate]) {
if (predicate == null && this is KtCollection) {
return (this as KtCollection).size;
}
var count = 0;
final Iterator<T> i = iter.iterator;
while (i.moveNext()) {
if (predicate == null) {
count++;
} else {
if (predicate(i.current)) {
count++;
}
}
}
return count;
}
/// Returns a list containing only distinct elements from the given collection.
///
/// The elements in the resulting list are in the same order as they were in the source collection.
KtList<T> distinct() => KtIterableExtensions<T>(toMutableSet()).toList();
/// Returns a list containing only elements from the given collection
/// having distinct keys returned by the given [selector] function.
///
/// The elements in the resulting list are in the same order as they were in the source collection.
KtList<T> distinctBy<K>(K Function(T) selector) {
final set = hashSetOf<K>();
final list = mutableListOf<T>();
for (final element in iter) {
final key = selector(element);
if (set.add(key)) {
list.add(element);
}
}
return list;
}
/// Returns a list containing all elements except first [n] elements.
KtList<T> drop(int n) {
// TODO add exception if n is negative
final list = mutableListOf<T>();
var count = 0;
for (final item in iter) {
if (count++ >= n) {
list.add(item);
}
}
return list;
}
/// Returns a list containing all elements except first elements that satisfy the given [predicate].
KtList<T> dropWhile(bool Function(T) predicate) {
var yielding = false;
final list = mutableListOf<T>();
for (final item in iter) {
if (yielding) {
list.add(item);
} else {
if (!predicate(item)) {
list.add(item);
yielding = true;
}
}
}
return list;
}
/// Returns an element at the given [index] or throws an [IndexOutOfBoundsException] if the [index] is out of bounds of this collection.
T elementAt(int index) {
return elementAtOrElse(index, (int index) {
throw IndexOutOfBoundsException(
"Collection doesn't contain element at index: $index.");
});
}
/// Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this collection.
T elementAtOrElse(int index, T Function(int) defaultValue) {
if (index < 0) {
return defaultValue(index);
}
final i = iterator();
int count = 0;
while (i.hasNext()) {
final element = i.next();
if (index == count++) {
return element;
}
}
return defaultValue(index);
}
/// Returns an element at the given [index] or `null` if the [index] is out of bounds of this collection.
T? elementAtOrNull(int index) {
if (index < 0) {
return null;
}
final i = iterator();
int count = 0;
while (i.hasNext()) {
final element = i.next();
if (index == count++) {
return element;
}
}
return null;
}
/// Returns a list containing only elements matching the given [predicate].
KtList<T> filter(bool Function(T) predicate) {
final filtered = filterTo(mutableListOf<T>(), predicate);
// TODO ping dort-lang/sdk team to check type bug
// When in single line: type "DartMutableList<String>' is not a subtype of type 'Null"
return filtered;
}
/// Returns a list containing only elements matching the given [predicate].
/// @param [predicate] function that takes the index of an element and the element itself
/// and returns the result of predicate evaluation on the element.
KtList<T> filterIndexed(bool Function(int index, T) predicate) {
final filtered = filterIndexedTo(mutableListOf<T>(), predicate);
// TODO ping dort-lang/sdk team to check type bug
// When in single line: type "DartMutableList<String>' is not a subtype of type 'Null"
return filtered;
}
/// Appends all elements matching the given [predicate] to the given [destination].
/// @param [predicate] function that takes the index of an element and the element itself
/// and returns the result of predicate evaluation on the element.
///
/// [destination] is not type checked by the compiler due to https://github.com/dart-lang/sdk/issues/35518,
/// but will be checked at runtime.
/// [C] actually is expected to be `C extends KtMutableCollection<T>`
// TODO Change to `C extends KtMutableCollection<T>` once https://github.com/dart-lang/sdk/issues/35518 has been fixed
C filterIndexedTo<C extends KtMutableCollection<dynamic>>(
C destination, bool Function(int index, T) predicate) {
assert(() {
if (destination is! KtMutableCollection<T> && mutableListOf<T>() is! C) {
throw ArgumentError(
"filterIndexedTo destination has wrong type parameters."
"\nExpected: KtMutableCollection<$T>, Actual: ${destination.runtimeType}"
"\ndestination (${destination.runtimeType}) entries aren't subtype of "
"map ($runtimeType) entries. Entries can't be copied to destination."
"\n\n$kBug35518GenericTypeError");
}
return true;
}());
var i = 0;
for (final element in iter) {
if (predicate(i++, element)) {
destination.add(element);
}
}
return destination;
}
/// Returns a list containing all elements that are instances of specified type parameter R.
KtList<R> filterIsInstance<R>() {
final destination = mutableListOf<R>();
for (final element in iter) {
if (element is R) {
destination.add(element);
}
}
return destination;
}
/// Returns a list containing all elements not matching the given [predicate].
KtList<T> filterNot(bool Function(T) predicate) {
final list = filterNotTo(mutableListOf<T>(), predicate);
// TODO ping dort-lang/sdk team to check type bug
// When in single line: type "DartMutableList<String>' is not a subtype of type 'Null"
return list;
}
/// Appends all elements not matching the given [predicate] to the given [destination].
///
/// [destination] is not type checked by the compiler due to https://github.com/dart-lang/sdk/issues/35518,
/// but will be checked at runtime.
/// [C] actually is expected to be `C extends KtMutableCollection<T>`
// TODO Change to `C extends KtMutableCollection<T>` once https://github.com/dart-lang/sdk/issues/35518 has been fixed
C filterNotTo<C extends KtMutableCollection<dynamic>>(
C destination, bool Function(T) predicate) {
assert(() {
if (destination is! KtMutableCollection<T> && mutableListOf<T>() is! C) {
throw ArgumentError("filterNotTo destination has wrong type parameters."
"\nExpected: KtMutableCollection<$T>, Actual: ${destination.runtimeType}"
"\ndestination (${destination.runtimeType}) entries aren't subtype of "
"map ($runtimeType) entries. Entries can't be copied to destination."
"\n\n$kBug35518GenericTypeError");
}
return true;
}());
for (final element in iter) {
if (!predicate(element)) {
destination.add(element);
}
}
return destination;
}
/// Appends all elements matching the given [predicate] to the given [destination].
///
/// [destination] is not type checked by the compiler due to https://github.com/dart-lang/sdk/issues/35518,
/// but will be checked at runtime.
/// [C] actually is expected to be `C extends KtMutableCollection<T>`
// TODO Change to `C extends KtMutableCollection<T>` once https://github.com/dart-lang/sdk/issues/35518 has been fixed
C filterTo<C extends KtMutableCollection<dynamic>>(
C destination, bool Function(T) predicate) {
assert(() {
if (destination is! KtMutableCollection<T> && mutableListOf<T>() is! C) {
throw ArgumentError("filterTo destination has wrong type parameters."
"\nExpected: KtMutableCollection<$T>, Actual: ${destination.runtimeType}"
"\ndestination (${destination.runtimeType}) entries aren't subtype of "
"map ($runtimeType) entries. Entries can't be copied to destination."
"\n\n$kBug35518GenericTypeError");
}
return true;
}());
for (final element in iter) {
if (predicate(element)) {
destination.add(element);
}
}
return destination;
}
/// Returns the first element matching the given [predicate], or `null` if no such element was found.
T? find(bool Function(T) predicate) {
return firstOrNull(predicate);
}
/// Returns the last element matching the given [predicate], or `null` if no such element was found.
T? findLast(bool Function(T) predicate) {
return lastOrNull(predicate);
}
/// Returns first element.
///
/// Use [predicate] to return the first element matching the given [predicate]
///
/// @throws [NoSuchElementException] if the collection is empty.
T first([bool Function(T)? predicate]) {
if (predicate == null) {
final i = iterator();
if (!i.hasNext()) {
throw const NoSuchElementException("Collection is empty");
}
return i.next();
} else {
for (final element in iter) {
if (predicate(element)) return element;
}
throw const NoSuchElementException(
"Collection contains no element matching the predicate.");
}
}
/// Returns the first non-null value after applying the given [transform]
/// function, throwing a [NoSuchElementException] exception if there is no
/// such value.
R firstNotNullOf<R>(R? Function(T?) transform) {
final R? element = firstNotNullOfOrNull(transform);
if (element != null) {
return element;
} else {
throw const NoSuchElementException(
"No element of the collection was transformed to a non-null value.",
);
}
}
/// Returns the first non-null value after applying the given [transform]
/// function; `null` will be returned if there is no such value.
R? firstNotNullOfOrNull<R>(R? Function(T?) transform) {
final KtList<R> mappedList = mapNotNull(transform);
return mappedList.firstOrNull();
}
/// Returns the first element (matching [predicate] when provided), or `null` if the collection is empty.
T? firstOrNull([bool Function(T)? predicate]) {
if (predicate == null) {
if (this is KtList) {
final list = this as KtList<T>;
if (list.isEmpty()) {
return null;
} else {
return list[0];
}
}
final i = iterator();
if (!i.hasNext()) {
return null;
}
return i.next();
} else {
for (final element in iter) {
if (predicate(element)) return element;
}
return null;
}
}
/// Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.
KtList<R> flatMap<R>(KtIterable<R> Function(T) transform) {
final list = flatMapTo(mutableListOf<R>(), transform);
// making a temp variable here, it helps dart to get types right ¯\_(ツ)_/¯
// TODO ping dort-lang/sdk team to check that bug
return list;
}
/// Returns a single list of all elements yielded from results of [transform]
/// function being invoked on each element and its index in the original
/// collection.
KtList<R> flatMapIndexed<R>(KtIterable<R> Function(int index, T) transform) {
final list = flatMapIndexedTo(mutableListOf<R>(), transform);
// making a temp variable here, it helps dart to get types right ¯\_(ツ)_/¯
// TODO ping dort-lang/sdk team to check that bug
return list;
}
/// Appends all elements yielded from results of [transform] function being
/// invoked on each element and its index in the original collection, to the
/// given [destination].
C flatMapIndexedTo<R, C extends KtMutableCollection<R>>(
C destination, KtIterable<R> Function(int index, T) transform) {
var index = 0;
for (final element in iter) {
final list = transform(index++, element);
destination.addAll(list);
}
return destination;
}
/// Appends all elements yielded from results of [transform] function being invoked on each element of original collection, to the given [destination].
C flatMapTo<R, C extends KtMutableCollection<R>>(
C destination, KtIterable<R> Function(T) transform) {
for (final element in iter) {
final list = transform(element);
destination.addAll(list);
}
return destination;
}
/// Accumulates value starting with [initial] value and applying [operation] from left to right to current accumulator value and each element.
R fold<R>(R initial, R Function(R acc, T) operation) {
var accumulator = initial;
for (final element in iter) {
accumulator = operation(accumulator, element);
}
return accumulator;
}
/// Accumulates value starting with [initial] value and applying [operation] from left to right
/// to current accumulator value and each element with its index in the original collection.
/// @param [operation] function that takes the index of an element, current accumulator value
/// and the element itself, and calculates the next accumulator value.
R foldIndexed<R>(R initial, R Function(int index, R acc, T) operation) {
var index = 0;
var accumulator = initial;
for (final element in iter) {
accumulator = operation(index++, accumulator, element);
}
return accumulator;
}
/// Performs the given [action] on each element.
void forEach(void Function(T element) action) {
final i = iterator();
while (i.hasNext()) {
final element = i.next();
action(element);
}
}
/// Performs the given [action] on each element, providing sequential index with the element.
/// @param [action] function that takes the index of an element and the element itself
/// and performs the desired action on the element.
void forEachIndexed(void Function(int index, T element) action) {
var index = 0;
for (final item in iter) {
action(index++, item);
}
}
/// Groups elements of the original collection by the key returned by the given [keySelector] function
/// applied to each element and returns a map where each group key is associated with a list of corresponding elements.
///
/// The returned map preserves the entry iteration order of the keys produced from the original collection.
KtMap<K, KtList<T>> groupBy<K>(K Function(T) keySelector) {
final groups = linkedMapFrom<K, KtList<T>>();
for (final element in iter) {
final key = keySelector(element);
final list = KtMutableMapExtensions(groups)
.getOrPut(key, () => mutableListOf<T>()) as KtMutableList<T>;
list.add(element);
}
return groups;
}
/// Groups values returned by the [valueTransform] function applied to each element of the original collection
/// by the key returned by the given [keySelector] function applied to the element
/// and returns a map where each group key is associated with a list of corresponding values.
///
/// The returned map preserves the entry iteration order of the keys produced from the original collection.
KtMap<K, KtList<V>> groupByTransform<K, V>(
K Function(T) keySelector, V Function(T) valueTransform) {
final groups = linkedMapFrom<K, KtList<V>>();
for (final element in iter) {
final key = keySelector(element);
final list = KtMutableMapExtensions(groups)
.getOrPut(key, () => mutableListOf<V>()) as KtMutableList<V>;
list.add(valueTransform(element));
}
return groups;
}
/// Groups elements of the original collection by the key returned by the given [keySelector] function
/// applied to each element and puts to the [destination] map each group key associated with a list of corresponding elements.
///
/// [destination] is not type checked by the compiler due to https://github.com/dart-lang/sdk/issues/35518,
/// but will be checked at runtime.
/// `C` actually is expected to be `C extends KtMutableCollection<T>`
// TODO Change to `M extends KtMutableMap<K, KtMutableList<T>` once https://github.com/dart-lang/sdk/issues/35518 has been fixed
M groupByTo<K, M extends KtMutableMap<K, KtMutableList<dynamic>>>(
M destination, K Function(T) keySelector) {
assert(() {
if (destination is! KtMutableMap<K, KtMutableList<T>> &&
mutableMapFrom<K, KtMutableList<T>>() is! M) {
throw ArgumentError("groupByTo destination has wrong type parameters."
"\nExpected: KtMutableMap<K, KtMutableList<$T>, Actual: ${destination.runtimeType}"
"\ndestination (${destination.runtimeType}) entries aren't subtype of "
"map ($runtimeType) entries. Entries can't be copied to destination."
"\n\n$kBug35518GenericTypeError");
}
return true;
}());
for (final element in iter) {
final key = keySelector(element);
final list = KtMutableMapExtensions(destination)
.getOrPut(key, () => mutableListOf<T>());
list.add(element);
}
return destination;
}
/// Groups values returned by the [valueTransform] function applied to each element of the original collection
/// by the key returned by the given [keySelector] function applied to the element
/// and puts to the [destination] map each group key associated with a list of corresponding values.
///
/// @return The [destination] map.
M groupByToTransform<K, V, M extends KtMutableMap<K, KtMutableList<V>>>(
M destination, K Function(T) keySelector, V Function(T) valueTransform) {
for (final element in iter) {
final key = keySelector(element);
final list = destination.getOrPut(key, () => mutableListOf<V>());
list.add(valueTransform(element));
}
return destination;
}
/// Returns first index of [element], or -1 if the collection does not contain element.
int indexOf(T element) {
if (this is KtList) return (this as KtList).indexOf(element);
var index = 0;
for (final item in iter) {
if (element == item) return index;
index++;
}
return -1;
}
/// Returns index of the first element matching the given [predicate], or -1 if the collection does not contain such element.
int indexOfFirst(bool Function(T) predicate) {
var index = 0;
for (final item in iter) {
if (predicate(item)) {
return index;
}
index++;
}
return -1;
}
/// Returns index of the last element matching the given [predicate], or -1 if the collection does not contain such element.
int indexOfLast(bool Function(T) predicate) {
var lastIndex = -1;
var index = 0;
for (final item in iter) {
if (predicate(item)) {
lastIndex = index;
}
index++;
}
return lastIndex;
}
/// Returns a set containing all elements that are contained by both this set and the specified collection.
///
/// The returned set preserves the element iteration order of the original collection.
KtSet<T> intersect(KtIterable<T> other) {
final set = toMutableSet();
set.retainAll(other);
return set;
}
/// Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
///
/// If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
/// elements will be appended, followed by the [truncated] string (which defaults to "...").
String joinToString(
{String separator = ", ",
String prefix = "",
String postfix = "",
int limit = -1,
String truncated = "...",
String Function(T)? transform}) {
final buffer = StringBuffer();
buffer.write(prefix);
var count = 0;
for (final element in iter) {
if (++count > 1) buffer.write(separator);
if (limit >= 0 && count > limit) {
break;
} else {
if (transform == null) {
buffer.write(element);
} else {
buffer.write(transform(element));
}
}
}
if (limit >= 0 && count > limit) {
buffer.write(truncated);
}
buffer.write(postfix);
return buffer.toString();
}
/// Returns the last element matching the given [predicate].
/// @throws [NoSuchElementException] if no such element is found.
T last([bool Function(T)? predicate]) {
if (predicate == null) {
if (this is KtList) return (this as KtList<T>).last();
final i = iterator();
if (!i.hasNext()) {
throw const NoSuchElementException("Collection is empty");
}
var last = i.next();
while (i.hasNext()) {
last = i.next();
}
return last;
} else {
T? last;
var found = false;
for (final element in iter) {
if (predicate(element)) {
last = element;
found = true;
}
}
if (!found) {
throw const NoSuchElementException(
"Collection contains no element matching the predicate.");
}
return last!;
}
}
/// Returns last index of [element], or -1 if the collection does not contain element.
int lastIndexOf(T element) {
if (this is KtList) return (this as KtList).lastIndexOf(element);
var lastIndex = -1;
var index = 0;
for (final item in iter) {
if (element == item) {
lastIndex = index;
}
index++;
}
return lastIndex;
}
/// Returns the last element matching the given [predicate], or `null` if no such element was found.
T? lastOrNull([bool Function(T)? predicate]) {
if (predicate == null) {
if (this is KtList) {
final list = this as KtList<T>;
return list.isEmpty() ? null : list.get(list.lastIndex);
} else {
final i = iterator();
if (!i.hasNext()) {
return null;
}
var last = i.next();
while (i.hasNext()) {
last = i.next();
}
return last;
}
} else {
T? last;
for (final element in iter) {
if (predicate(element)) {
last = element;
}
}
return last;
}
}
/// Returns a list containing the results of applying the given [transform] function
/// to each element in the original collection.
KtList<R> map<R>(R Function(T) transform) {
final KtMutableList<R> list = mutableListOf<R>();
final mapped = mapTo(list, transform);
// TODO ping dort-lang/sdk team to check type bug
// When in single line: type "DartMutableList<String>' is not a subtype of type 'Null"
return mapped;
}
/// Returns a list containing the results of applying the given [transform] function
/// to each element and its index in the original collection.
/// @param [transform] function that takes the index of an element and the element itself
/// and returns the result of the transform applied to the element.
KtList<R> mapIndexed<R>(R Function(int index, T) transform) {
final mapped = mapIndexedTo(mutableListOf<R>(), transform);
// TODO ping dort-lang/sdk team to check type bug
// When in single line: type "DartMutableList<String>' is not a subtype of type 'Null"
return mapped;
}
/// Applies the given [transform] function to each element and its index in the original collection
/// and appends the results to the given [destination].
/// @param [transform] function that takes the index of an element and the element itself
/// and returns the result of the transform applied to the element.
C mapIndexedTo<R, C extends KtMutableCollection<R>>(
C destination, R Function(int index, T) transform) {
var index = 0;
for (final item in iter) {
destination.add(transform(index++, item));
}
return destination;
}
/// Applies the given [transform] function to each element of the original collection
/// and appends the results to the given [destination].
C mapTo<R, C extends KtMutableCollection<R>>(
C destination, R Function(T) transform) {
for (final item in iter) {
destination.add(transform(item));
}
return destination;
}
/// Returns the first element yielding the largest value of the given function or `null` if there are no elements.
T? maxBy<R extends Comparable>(R Function(T) selector) {
final i = iterator();