-
Notifications
You must be signed in to change notification settings - Fork 86
/
iterable.dart
1387 lines (1262 loc) · 41 KB
/
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:collection';
import 'dart:math';
import 'package:collection/collection.dart' as collection;
import 'package:dartx/src/sorted_list.dart';
extension IterableSecondItem<E> on Iterable<E> {
/// Second element.
///
/// ```dart
/// [1, 2, 3].second; // 2
/// ```
E get second => elementAt(1);
}
extension IterableThirdItem<E> on Iterable<E> {
/// Third element.
///
/// ```dart
/// [1, 2, 3].third; // 3
/// ```
E get third => elementAt(2);
}
extension IterableFourthItem<E> on Iterable<E> {
/// Fourth element.
///
/// ```dart
/// [1, 2, 3, 4].fourth; // 4
/// ```
E get fourth => elementAt(3);
}
extension IterableElementAtOrNull<E> on Iterable<E> {
/// Returns an element at the given [index] or `null` if the [index] is out of
/// bounds of this collection.
///
/// ```dart
/// final list = [1, 2, 3, 4];
/// final first = list.elementAtOrNull(0); // 1
/// final fifth = list.elementAtOrNull(4); // null
/// ```
E? elementAtOrNull(int index) {
if (index < 0) return null;
var count = 0;
for (final element in this) {
if (index == count++) return element;
}
return null;
}
}
extension IterableElementAtOrDefault<E> on Iterable<E> {
/// Returns an element at the given [index] or [defaultValue] if the [index]
/// is out of bounds of this collection.
///
/// ```dart
/// final list = [1, 2, 3, 4];
/// final first = list.elementAtOrDefault(0, -1); // 1
/// final fifth = list.elementAtOrDefault(4, -1); // -1
/// ```
E elementAtOrDefault(int index, E defaultValue) {
return elementAtOrElse(index, (_) => defaultValue);
}
}
extension IterableElementAtOrElse<E> on Iterable<E> {
/// 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.
///
/// ```dart
/// final list = [1, 2, 3, 4];
/// final first = list.elementAtOrElse(0); // 1
/// final fifth = list.elementAtOrElse(4, -1); // -1
/// ```
E elementAtOrElse(int index, E Function(int index) defaultValue) {
if (index < 0) return defaultValue(index);
var count = 0;
for (final element in this) {
if (index == count++) return element;
}
return defaultValue(index);
}
}
extension IterableFirstOrNull<E> on Iterable<E> {
/// First element or `null` if the collection is empty.
///
/// ```dart
/// final first = [1, 2, 3, 4].firstOrNull; // 1
/// final emptyFirst = [].firstOrNull; // null
/// ```
E? get firstOrNull => isNotEmpty ? first : null;
}
extension IterableFirstOrDefault<E> on Iterable<E> {
/// First element or `defaultValue` if the collection is empty.
///
/// ```dart
/// final first = [1, 2, 3, 4].firstOrDefault(-1); // 1
/// final emptyFirst = [].firstOrDefault(-1); // -1
/// ```
E firstOrDefault(E defaultValue) => isNotEmpty ? first : defaultValue;
}
extension IterableFirstOrNullWhere<E> on Iterable<E> {
/// Returns the first element matching the given [predicate], or `null` if no
/// such element was found.
///
/// ```dart
/// final list = ['a', 'Test'];
/// final firstLong= list.firstOrNullWhere((e) => e.length > 1); // 'Test'
/// final firstVeryLong = list.firstOrNullWhere((e) => e.length > 5); // null
/// ```
E? firstOrNullWhere(bool Function(E element) predicate) {
for (final element in this) {
if (predicate(element)) return element;
}
return null;
}
}
extension IterableLastOrNull<E> on Iterable<E> {
/// Last element or `null` if the collection is empty.
///
/// ```dart
/// final last = [1, 2, 3, 4].lastOrNull; // 4
/// final emptyLast = [].firstOrNull; // null
/// ```
E? get lastOrNull => isNotEmpty ? last : null;
}
extension IterableLastOrElse<E> on Iterable<E> {
/// Last element or `defaultValue` if the collection is empty.
E lastOrElse(E defaultValue) =>
IterableLastOrNull(this).lastOrNull ?? defaultValue;
}
extension IterableLastOrNullWhere<E> on Iterable<E> {
/// Returns the last element matching the given [predicate], or `null` if no
/// such element was found.
E? lastOrNullWhere(bool Function(E element) predicate) {
E? match;
for (final e in this) {
if (predicate(e)) {
match = e;
}
}
return match;
}
}
extension IterableAll<E> on Iterable<E> {
/// Returns true if all elements match the given [predicate] or if the
/// collection is empty.
bool all(bool Function(E element) predicate) {
for (final element in this) {
if (!predicate(element)) {
return false;
}
}
return true;
}
}
extension IterableNone<E> on Iterable<E> {
/// Returns true if no entries match the given [predicate] or if the
/// collection is empty.
bool none(bool Function(E element) predicate) => !any(predicate);
}
extension IterableSlice<E> on Iterable<E> {
/// Returns a new list containing elements at indices between [start]
/// (inclusive) and [end] (inclusive).
///
/// If [end] is omitted, it is being set to `lastIndex`.
List<E> slice(int start, [int end = -1]) {
final list = this is List ? this as List<E> : toList();
var _start = start;
var _end = end;
if (_start < 0) {
_start = _start + list.length;
}
if (_end < 0) {
_end = _end + list.length;
}
RangeError.checkValidRange(_start, _end, list.length);
return list.sublist(_start, _end + 1);
}
}
extension IterableForEachIndexed<E> on Iterable<E> {
/// Performs the given [action] on each element, providing sequential index
/// with the element.
void forEachIndexed(void Function(E element, int index) action) {
var index = 0;
for (final element in this) {
action(element, index++);
}
}
}
extension IterableContainsAll<E> on Iterable<E> {
/// Checks if all elements in the specified [collection] are contained in
/// this collection.
bool containsAll(Iterable<E> collection) {
for (final element in collection) {
if (!contains(element)) return false;
}
return true;
}
}
extension IterableContainsAny<E> on Iterable<E> {
/// Checks if any elements in the specified [collection] are contained in
/// this collection.
bool containsAny(Iterable<E> collection) {
for (final element in collection) {
if (contains(element)) return true;
}
return false;
}
}
extension IterableContentEquals<E> on Iterable<E> {
/// Returns true if this collection is structurally equal to the [other]
/// collection.
///
/// I.e. contain the same number of the same elements in the same order.
///
/// If [checkEqual] is provided, it is used to check if two elements are the
/// same.
bool contentEquals(Iterable<E> other, [bool Function(E a, E b)? checkEqual]) {
final it1 = iterator;
final it2 = other.iterator;
if (checkEqual != null) {
while (it1.moveNext()) {
if (!it2.moveNext()) return false;
if (!checkEqual(it1.current, it2.current)) return false;
}
} else {
while (it1.moveNext()) {
if (!it2.moveNext()) return false;
if (it1.current != it2.current) return false;
}
}
return !it2.moveNext();
}
}
extension IterableSorted<E> on Iterable<E> {
/// Returns a new list with all elements sorted according to natural sort
/// order.
List<E> sorted() {
final list = toList();
list.sort();
return list;
}
}
extension IterableSortedDescending<E> on Iterable<E> {
/// Returns a new list with all elements sorted according to descending
/// natural sort order.
List<E> sortedDescending() {
final list = toList();
list.sort((a, b) => -(a as Comparable).compareTo(b));
return list;
}
}
extension IterableSortedBy<E> on Iterable<E> {
/// Returns a new list with all elements sorted according to natural sort
/// order of the values returned by specified [selector] function.
///
/// To sort by more than one property, `thenBy()` or `thenByDescending()` can
/// be called afterwards.
///
/// **Note:** The actual sorting is performed when an element is accessed for
/// the first time.
SortedList<E> sortedBy(Comparable Function(E element) selector) {
return SortedList<E>.withSelector(this, selector, 1, null);
}
}
extension IterableSortedByDescending<E> on Iterable<E> {
/// Returns a new list with all elements sorted according to descending
/// natural sort order of the values returned by specified [selector]
/// function.
///
/// To sort by more than one property, `thenBy()` or `thenByDescending` can
/// be called afterwards.
///
/// **Note:** The actual sorting is performed when an element is accessed for
/// the first time.
SortedList<E> sortedByDescending(Comparable Function(E element) selector) {
return SortedList<E>.withSelector(this, selector, -1, null);
}
}
extension IterableSortedWith<E> on Iterable<E> {
/// Returns a new list with all elements sorted according to specified
/// [comparator].
///
/// To sort by more than one property, `thenBy()` or `thenByDescending` can
/// be called afterwards.
///
/// **Note:** The actual sorting is performed when an element is accessed for
/// the first time.
SortedList<E> sortedWith(Comparator<E> comparator) {
return SortedList<E>(this, comparator);
}
}
extension IterableJoinToString<E> on Iterable<E> {
/// 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 Function(E element)? transform,
String prefix = '',
String postfix = '',
int? limit,
String truncated = '...',
}) {
final buffer = StringBuffer();
var count = 0;
for (final element in this) {
if (limit != null && count >= limit) {
buffer.write(truncated);
return buffer.toString();
}
if (count > 0) {
buffer.write(separator);
}
buffer.write(prefix);
if (transform != null) {
buffer.write(transform(element));
} else {
buffer.write(element.toString());
}
buffer.write(postfix);
count++;
}
return buffer.toString();
}
}
extension IterableSumBy<E> on Iterable<E> {
/// Returns the sum of all values produced by [selector] function applied to
/// each element in the collection.
T sumBy<T extends num>(T Function(E element) selector) {
var sum = T == double ? 0.0 : 0;
for (final current in this) {
sum += selector(current);
}
return sum as T;
}
}
extension IterableAverageBy<E> on Iterable<E> {
/// Returns the average of values returned by [selector] for all elements in
/// the collection.
double averageBy(num Function(E element) selector) {
var count = 0;
num sum = 0;
for (final current in this) {
sum += selector(current);
count++;
}
if (count == 0) {
throw StateError('No elements in collection');
} else {
return sum / count;
}
}
}
extension InterableMin<E> on Iterable<E> {
/// Returns the smallest element or `null` if there are no elements.
///
/// All elements must be of type [Comparable].
E? min() => _minMax(-1);
}
extension _MinMaxHelper<E> on Iterable<E> {
E? _minMax(int order) {
final it = iterator;
if (!it.moveNext()) {
return null;
}
var currentMin = it.current;
if (order < 0) {
while (it.moveNext()) {
if ((it.current as Comparable).compareTo(currentMin) <= order) {
currentMin = it.current;
}
}
} else {
while (it.moveNext()) {
if ((it.current as Comparable).compareTo(currentMin) >= order) {
currentMin = it.current;
}
}
}
return currentMin;
}
E? _minMaxBy(int order, Comparable Function(E element) selector) {
final it = iterator;
if (!it.moveNext()) {
return null;
}
var currentMin = it.current;
var currentMinValue = selector(it.current);
while (it.moveNext()) {
final comp = selector(it.current);
if (comp.compareTo(currentMinValue) == order) {
currentMin = it.current;
currentMinValue = comp;
}
}
return currentMin;
}
E? _minMaxWith(int order, Comparator<E> comparator) {
final it = iterator;
if (!it.moveNext()) {
return null;
}
var currentMin = it.current;
while (it.moveNext()) {
if (comparator(it.current, currentMin) == order) {
currentMin = it.current;
}
}
return currentMin;
}
}
extension IterableMinBy<E> on Iterable<E> {
/// Returns the first element yielding the smallest value of the given
/// [selector] or `null` if there are no elements.
E? minBy(Comparable Function(E element) selector) => _minMaxBy(-1, selector);
}
extension IterableMinWith<E> on Iterable<E> {
/// Returns the first element having the smallest value according to the
/// provided [comparator] or `null` if there are no elements.
E? minWith(Comparator<E> comparator) => _minMaxWith(-1, comparator);
}
extension IterableMax<E> on Iterable<E> {
/// Returns the largest element or `null` if there are no elements.
///
/// All elements must be of type [Comparable].
E? max() => _minMax(1);
}
extension IterableMaxBy<E> on Iterable<E> {
/// Returns the first element yielding the largest value of the given
/// [selector] or `null` if there are no elements.
E? maxBy(Comparable Function(E element) selector) => _minMaxBy(1, selector);
}
extension IterableMaxWith<E> on Iterable<E> {
/// Returns the first element having the largest value according to the
/// provided [comparator] or `null` if there are no elements.
E? maxWith(Comparator<E> comparator) => _minMaxWith(1, comparator);
}
extension IterableCount<E> on Iterable<E> {
/// Returns the number of elements matching the given [predicate].
///
/// If no [predicate] is given, this equals to [length].
int count([bool Function(E element)? predicate]) {
var count = 0;
if (predicate == null) {
return length;
} else {
for (final current in this) {
if (predicate(current)) {
count++;
}
}
}
return count;
}
}
extension IterableReversed<E> on Iterable<E> {
/// Returns an [Iterable] of the objects in this list in reverse order.
Iterable<E> get reversed {
return this is List<E> ? (this as List<E>).reversed : toList().reversed;
}
}
extension IterableTakeFirst<E> on Iterable<E> {
/// Returns a list containing first [n] elements.
///
/// ```dart
/// val chars = [1, 2, 3, 4, 5, 6, 7, 8, 9];
/// print(chars.take(3)) // [1, 2, 3]
/// print(chars.takeWhile((it) => it < 5) // [1, 2, 3, 4]
/// print(chars.takeLast(2)) // [8, 9]
/// print(chars.takeLastWhile((it) => it > 5 }) // [6, 7, 8, 9]
/// ```
List<E> takeFirst(int n) {
final list = this is List<E> ? this as List<E> : toList();
return list.take(n).toList();
}
}
extension IterableTakeLast<E> on Iterable<E> {
/// Returns a list containing last [n] elements.
///
/// ```dart
/// val chars = [1, 2, 3, 4, 5, 6, 7, 8, 9];
/// print(chars.take(3)) // [1, 2, 3]
/// print(chars.takeWhile((it) => it < 5) // [1, 2, 3, 4]
/// print(chars.takeLast(2)) // [8, 9]
/// print(chars.takeLastWhile((it) => it > 5 }) // [6, 7, 8, 9]
/// ```
List<E> takeLast(int n) {
final list = this is List<E> ? this as List<E> : toList();
return list.reversed.take(n).reversed.toList();
}
}
extension IterableFirstWhile<E> on Iterable<E> {
//// Returns the first elements satisfying the given [predicate].
///
/// ```dart
/// val chars = [1, 2, 3, 4, 5, 6, 7, 8, 9];
/// print(chars.take(3)) // [1, 2, 3]
/// print(chars.takeWhile((it) => it < 5) // [1, 2, 3, 4]
/// print(chars.takeLast(2)) // [8, 9]
/// print(chars.takeLastWhile((it) => it > 5 }) // [6, 7, 8, 9]
/// ```
Iterable<E> firstWhile(bool Function(E element) predicate) sync* {
for (final element in this) {
if (!predicate(element)) break;
yield element;
}
}
}
extension IterableLastWhile<E> on Iterable<E> {
/// Returns the last elements satisfying the given [predicate].
///
/// ```dart
/// val chars = [1, 2, 3, 4, 5, 6, 7, 8, 9];
/// print(chars.take(3)) // [1, 2, 3]
/// print(chars.takeWhile((it) => it < 5) // [1, 2, 3, 4]
/// print(chars.takeLast(2)) // [8, 9]
/// print(chars.takeLastWhile((it) => it > 5 }) // [6, 7, 8, 9]
/// ```
Iterable<E> lastWhile(bool Function(E element) predicate) {
final list = ListQueue<E>();
for (final element in reversed) {
if (!predicate(element)) break;
list.addFirst(element);
}
return list;
}
}
extension IterableFilter<E> on Iterable<E> {
/// Returns all elements matching the given [predicate].
Iterable<E> filter(bool Function(E element) predicate) => where(predicate);
}
extension IterableFilterIndexed<E> on Iterable<E> {
/// Returns all elements that satisfy the given [predicate].
Iterable<E> filterIndexed(bool Function(E element, int index) predicate) =>
IterableWhereIndexed(this).whereIndexed(predicate);
}
extension IterableFilterTo<E> on Iterable<E> {
/// Appends all elements matching the given [predicate] to the given
/// [destination].
void filterTo(List<E> destination, bool Function(E element) predicate) =>
whereTo(destination, predicate);
}
extension IterableFilterIndexedTo<E> on Iterable<E> {
/// Appends all elements matching the given [predicate] to the given
/// [destination].
void filterIndexedTo(
List<E> destination,
bool Function(E element, int index) predicate,
) =>
whereIndexedTo(destination, predicate);
}
extension IterableFilterNot<E> on Iterable<E> {
/// Returns all elements not matching the given [predicate].
Iterable<E> filterNot(bool Function(E element) predicate) =>
IterableWhereNot(this).whereNot(predicate);
}
extension IterableFilterNotIndexed<E> on Iterable<E> {
/// Returns all elements not matching the given [predicate].
Iterable<E> filterNotIndexed(bool Function(E element, int index) predicate) =>
IterableWhereNotIndexed(this).whereNotIndexed(predicate);
}
extension IterableFilterNotTo<E> on Iterable<E> {
/// Appends all elements not matching the given [predicate] to the given
/// [destination].
void filterNotTo(List<E> destination, bool Function(E element) predicate) =>
whereNotTo(destination, predicate);
}
extension IterableFilterNotToIndexed<E> on Iterable<E> {
/// Appends all elements not matching the given [predicate] to the given
/// [destination].
void filterNotToIndexed(
List<E> destination,
bool Function(E element, int index) predicate,
) =>
whereNotToIndexed(destination, predicate);
}
extension IterableFilterNotNull<E> on Iterable<E?> {
/// Returns a new lazy [Iterable] with all elements which are not null.
Iterable<E> filterNotNull() => whereNotNull();
}
extension IterableWhereIndexed<E> on Iterable<E> {
/// Returns all elements that satisfy the given [predicate].
Iterable<E> whereIndexed(
bool Function(E element, int index) predicate,
) sync* {
var index = 0;
for (final element in this) {
if (predicate(element, index++)) {
yield element;
}
}
}
}
extension IterableWhereTo<E> on Iterable<E> {
/// Appends all elements matching the given [predicate] to the given
/// [destination].
void whereTo(List<E> destination, bool Function(E element) predicate) {
for (final element in this) {
if (predicate(element)) {
destination.add(element);
}
}
}
}
extension IterableWhereIndexedTo<E> on Iterable<E> {
/// Appends all elements matching the given [predicate] to the given
/// [destination].
void whereIndexedTo(
List<E> destination,
bool Function(E element, int index) predicate,
) {
var index = 0;
for (final element in this) {
if (predicate(element, index++)) {
destination.add(element);
}
}
}
}
extension IterableWhereNot<E> on Iterable<E> {
/// Returns all elements not matching the given [predicate].
Iterable<E> whereNot(bool Function(E element) predicate) sync* {
for (final element in this) {
if (!predicate(element)) {
yield element;
}
}
}
}
extension IterableWhereNotIndexed<E> on Iterable<E> {
/// Returns all elements not matching the given [predicate].
Iterable<E> whereNotIndexed(
bool Function(E element, int index) predicate,
) sync* {
var index = 0;
for (final element in this) {
if (!predicate(element, index++)) {
yield element;
}
}
}
}
extension IterableWhereNotTo<E> on Iterable<E> {
/// Appends all elements not matching the given [predicate] to the given
/// [destination].
void whereNotTo(List<E> destination, bool Function(E element) predicate) {
for (final element in this) {
if (!predicate(element)) {
destination.add(element);
}
}
}
}
extension IterableWhereNotToIndexed<E> on Iterable<E> {
/// Appends all elements not matching the given [predicate] to the given
/// [destination].
void whereNotToIndexed(
List<E> destination,
bool Function(E element, int index) predicate,
) {
var index = 0;
for (final element in this) {
if (!predicate(element, index++)) {
destination.add(element);
}
}
}
}
extension IterableWhereNotNull<E> on Iterable<E?> {
/// Returns a new lazy [Iterable] with all elements which are not null.
Iterable<E> whereNotNull() => where((element) => element != null).cast<E>();
}
extension IterableMapNotNull<E> on Iterable<E> {
/// Returns a new lazy [Iterable] containing only the non-null results of
/// applying the given [transform] function to each element in the original
/// collection.
Iterable<R> mapNotNull<R>(R? Function(E element) transform) sync* {
for (final element in this) {
final result = transform(element);
if (result != null) {
yield result;
}
}
}
}
extension IterableMapIndexed<E> on Iterable<E> {
/// Returns a new lazy [Iterable] containing the results of applying the
/// given [transform] function to each element and its index in the original
/// collection.
Iterable<R> mapIndexed<R>(R Function(int index, E) transform) sync* {
var index = 0;
for (final element in this) {
yield transform(index++, element);
}
}
}
extension IterableMapIndexedNotNull<E> on Iterable<E> {
/// Returns a new lazy [Iterable] containing only the non-null results of
/// applying the given [transform] function to each element and its index
/// in the original collection.
Iterable<R> mapIndexedNotNull<R>(R? Function(int index, E) transform) sync* {
var index = 0;
for (final element in this) {
final result = transform(index++, element);
if (result != null) {
yield result;
}
}
}
}
extension IterableOnEach<E> on Iterable<E> {
/// Returns a new lazy [Iterable] which performs the given action on each
/// element.
Iterable<E> onEach(void Function(E element) action) sync* {
for (final element in this) {
action(element);
yield element;
}
}
}
extension IterableDistinct<E> on Iterable<E> {
/// Returns a new lazy [Iterable] containing only distinct elements from the
/// collection.
///
/// The elements in the resulting list are in the same order as they were in
/// the source collection.
Iterable<E> distinct() sync* {
final existing = HashSet<E>();
for (final current in this) {
if (existing.add(current)) {
yield current;
}
}
}
}
extension IterableDistinctBy<E> on Iterable<E> {
/// Returns a new lazy [Iterable] containing only elements from the 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.
Iterable<E> distinctBy<R>(R Function(E element) selector) sync* {
final existing = HashSet<R>();
for (final current in this) {
if (existing.add(selector(current))) {
yield current;
}
}
}
}
extension IterableChunked<E> on Iterable<E> {
/// Splits this collection into a new lazy [Iterable] of lists each not
/// exceeding the given [size].
///
/// The last list in the resulting list may have less elements than the given
/// [size].
///
/// [size] must be positive and can be greater than the number of elements in
/// this collection.
Iterable<List<E>> chunked(int size) sync* {
if (size < 1) {
throw ArgumentError('Requested chunk size $size is less than one.');
}
var currentChunk = <E>[];
for (final current in this) {
currentChunk.add(current);
if (currentChunk.length >= size) {
yield currentChunk;
currentChunk = <E>[];
}
}
if (currentChunk.isNotEmpty) {
yield currentChunk;
}
}
}
extension IterableChunkWhile<E> on Iterable<E> {
/// Splits this collection into a lazy [Iterable] of chunks, where chunks are
/// created as long as [predicate] is true for a pair of entries.
///
/// For example, one-by-one increasing subsequences can be chunked as follows:
/// ```dart
/// final list = [1, 2, 4, 9, 10, 11, 12, 15, 16, 19, 20, 21];
/// final increasingSubSequences = list.chunkWhile((a, b) => a + 1 == b);
/// ```
///
/// Here, `increasingSubSequences` would consist of `[1, 2]`, `[4]`,
/// `[9, 10, 11]`, `[12]`, `[15, 16]` and finally `[19, 20, 21]`.
///
/// See also:
/// - [splitWhen], which works similarly but with a reverted [predicate].
Iterable<List<E>> chunkWhile(bool Function(E, E) predicate) sync* {
var currentChunk = <E>[];
var hasPrevious = false;
late E previous;
for (final element in this) {
if (!hasPrevious || predicate(previous, element)) {
// keep element in current chunk
currentChunk.add(element);
} else {
// start a new chunk containing the new element
yield currentChunk;
currentChunk = [element];
}
previous = element;
hasPrevious = true;
}
if (currentChunk.isNotEmpty) yield currentChunk;
}
}
extension IterableSplitWhen<E> on Iterable<E> {
/// Splits this collection into a lazy [Iterable], where each split will be
/// make if [predicate] returns true for a pair of entries.
///
/// For example, one could split the iterable at each changed value like this:
/// ```dart
/// final list = [1, 1, 1, 2, 2, 1, 4, 4];
/// final splitted = list.splitWhen((a, b) => a != b);
/// ```
///
/// In that example, `splitted` would consist of `[1, 1, 1, 1]`, `[2, 2]`,
/// `[1]`, `[4, 4]`.
///
/// See also:
/// - [chunkWhile], which works similarly but with a reverted [predicate].
Iterable<List<E>> splitWhen(bool Function(E, E) predicate) {
return chunkWhile((a, b) => !predicate(a, b));
}
}
extension IterableWindowed<E> on Iterable<E> {
/// Returns a new lazy [Iterable] of windows of the given [size] sliding along
/// this collection with the given [step].
///
/// The last list may have less elements than the given size.
///
/// Both [size] and [step] must be positive and can be greater than the number
/// of elements in this collection.
Iterable<List<E>> windowed(
int size, {
int step = 1,
bool partialWindows = false,
}) sync* {
final gap = step - size;
if (gap >= 0) {
var buffer = <E>[];
var skip = 0;
for (final element in this) {
if (skip > 0) {
skip -= 1;
continue;
}
buffer.add(element);
if (buffer.length == size) {
yield buffer;
buffer = <E>[];
skip = gap;
}
}
if (buffer.isNotEmpty && (partialWindows || buffer.length == size)) {
yield buffer;
}
} else {
final buffer = ListQueue<E>(size);
for (final element in this) {
buffer.add(element);
if (buffer.length == size) {
yield buffer.toList();
for (var i = 0; i < step; i++) {
buffer.removeFirst();
}
}
}
if (partialWindows) {
while (buffer.length > step) {
yield buffer.toList();
for (var i = 0; i < step; i++) {
buffer.removeFirst();
}
}
if (buffer.isNotEmpty) {
yield buffer.toList();
}
}
}
}
}
extension IterableFlatMap<E> on Iterable<E> {
/// Returns a new lazy [Iterable] of all elements yielded from results of
/// [transform] function being invoked on each element of this collection.
Iterable<R> flatMap<R>(Iterable<R> Function(E element) transform) sync* {
for (final current in this) {
yield* transform(current);
}
}
}
extension IterableCycle<E> on Iterable<E> {
/// Returns a new lazy [Iterable] which iterates over this collection [n]
/// times.
///
/// When it reaches the end, it jumps back to the beginning. Returns `null`
/// [n] times if the collection is empty.
///
/// If [n] is omitted, the Iterable cycles forever.
Iterable<E> cycle([int? n]) sync* {
var it = iterator;
if (!it.moveNext()) {
return;
}
if (n == null) {
yield it.current;
// ignore: literal_only_boolean_expressions