-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathiter.php
1300 lines (1233 loc) · 33.7 KB
/
iter.php
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
<?php
namespace iter;
/**
* Creates an iterable containing all numbers between the start and end value
* (inclusive) with a certain step.
*
* Examples:
*
* iter\range(0, 5)
* => iter(0, 1, 2, 3, 4, 5)
* iter\range(5, 0)
* => iter(5, 4, 3, 2, 1, 0)
* iter\range(0.0, 3.0, 0.5)
* => iter(0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0)
* iter\range(3.0, 0.0, -0.5)
* => iter(3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.0)
*
* @param int|float $start First number (inclusive)
* @param int|float $end Last number (inclusive, but doesn't have to be part of
* resulting range if $step steps over it)
* @param int|float $step Step between numbers (defaults to 1 if $start smaller
* $end and to -1 if $start greater $end)
*
* @throws \InvalidArgumentException if step is not valid
*
* @return \Iterator<int|float>
*/
function range($start, $end, $step = null): \Iterator {
if ($start == $end) {
yield $start;
} elseif ($start < $end) {
if (null === $step) {
$step = 1;
} elseif ($step <= 0) {
throw new \InvalidArgumentException(
'If start < end the step must be positive'
);
}
for ($i = $start; $i <= $end; $i += $step) {
yield $i;
}
} else {
if (null === $step) {
$step = -1;
} elseif ($step >= 0) {
throw new \InvalidArgumentException(
'If start > end the step must be negative'
);
}
for ($i = $start; $i >= $end; $i += $step) {
yield $i;
}
}
}
/**
* Applies a mapping function to all values of an iterator.
*
* The function is passed the current iterator value and should return a
* modified iterator value. The key is left as-is and not passed to the mapping
* function.
*
* Examples:
*
* iter\map(iter\func\operator('*', 2), [1, 2, 3, 4, 5]);
* => iter(2, 4, 6, 8, 10)
*
* $column = map(iter\func\index('name'), $iter);
*
* @template T
* @template U
*
* @param callable(T):U $function Mapping function
* @param iterable<T> $iterable Iterable to be mapped over
*
* @return \Iterator<U>
*/
function map(callable $function, iterable $iterable): \Iterator {
foreach ($iterable as $key => $value) {
yield $key => $function($value);
}
}
/**
* Applies a mapping function to all keys of an iterator.
*
* The function is passed the current iterator key and should return a
* modified iterator key. The value is left as-is and not passed to the mapping
* function.
*
* Examples:
*
* iter\mapKeys('strtolower', ['A' => 1, 'B' => 2, 'C' => 3, 'D' => 4]);
* => iter('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4)
*
* @template TKey
* @template UKey
* @template Value
*
* @param callable(TKey):UKey $function Mapping function
* @param iterable<TKey,Value> $iterable Iterable those keys are to be mapped over
*
* @return \Iterator<UKey,Value>
*/
function mapKeys(callable $function, iterable $iterable): \Iterator {
foreach ($iterable as $key => $value) {
yield $function($key) => $value;
}
}
/**
* Applies a mapping function to all values of an iterator, passing both the key and the value into the callback.
*
* The function is passed the current iterator value and key and should return a
* modified iterator value. The key is left as-is but passed to the mapping
* function as the second parameter.
*
* Examples:
*
* iter\mapWithKeys(iter\func\operator('*'), range(0, 5));
* => iter(0, 1, 4, 9, 16, 25)
*
* iter\mapWithKeys(
* function ($v, $k) { return sprintf('%s%s', $k, $v); },
* ['foo' => 'bar', 'bing' => 'baz']
* );
* => iter(['foo' => 'foobar', 'bing' => 'bingbaz'])
*
* @template TKey
* @template T
* @template U
*
* @param callable(T,TKey):U $function Mapping function
* @param iterable<TKey,T> $iterable Iterable to be mapped over
*
* @return \Iterator<TKey,U>
*/
function mapWithKeys(callable $function, iterable $iterable): \Iterator {
foreach ($iterable as $key => $value) {
yield $key => $function($value, $key);
}
}
/**
* Applies a function to each value in an iterator and flattens the result.
*
* The function is passed the current iterator value and should return an
* iterator of new values. The result will be a concatenation of the iterators
* returned by the mapping function.
*
* Examples:
*
* iter\flatMap(function($v) { return [-$v, $v]; }, [1, 2, 3, 4, 5]);
* => iter(-1, 1, -2, 2, -3, 3, -4, 4, -5, 5)
*
* @template T
* @template U
*
* @param callable(T):iterable<U> $function Mapping function
* @param iterable<T> $iterable Iterable to be mapped over
*
* @return \Iterator<U>
*/
function flatMap(callable $function, iterable $iterable): \Iterator {
foreach ($iterable as $value) {
yield from $function($value);
}
}
/**
* Reindexes an array by applying a function to all values of an iterator and
* using the returned value as the new key/index.
*
* The function is passed the current iterator value and should return a new
* key for that element. The value is left as-is. The original key is not passed
* to the mapping function.
*
* Examples:
*
* $users = [
* ['id' => 42, 'name' => 'foo'],
* ['id' => 24, 'name' => 'bar']
* ];
* iter\reindex(iter\func\index('id'), $users)
* => iter(
* 42 => ['id' => 42, 'name' => 'foo'],
* 24 => ['id' => 24, 'name' => 'bar']
* )
*
* @template TKey
* @template UKey
* @template Value
*
* @param callable(Value):UKey $function Mapping function
* @param iterable<TKey,Value> $iterable Iterable to reindex
*
* @return \Iterator<UKey,Value>
*/
function reindex(callable $function, iterable $iterable): \Iterator {
foreach ($iterable as $value) {
yield $function($value) => $value;
}
}
/**
* Applies a function to all values of an iterable.
*
* The function is passed the current iterator value. The reason why apply
* exists additionally to map is that map is lazy, whereas apply is not (i.e.
* you do not need to consume a resulting iterator for the function calls to
* actually happen.)
*
* Examples:
*
* iter\apply(iter\func\method('rewind'), $iterators);
*
* @template T
*
* @param callable(T):void $function Apply function
* @param iterable<T> $iterable Iterator to apply on
*/
function apply(callable $function, iterable $iterable): void {
foreach ($iterable as $value) {
$function($value);
}
}
/**
* Filters an iterable using a predicate.
*
* The predicate is passed the iterator value, which is only retained if the
* predicate returns a truthy value. The key is not passed to the predicate and
* left as-is.
*
* Examples:
*
* iter\filter(iter\func\operator('<', 0), [0, -1, -10, 7, 20, -5, 7]);
* => iter(-1, -10, -5)
*
* iter\filter(iter\func\operator('instanceof', 'SomeClass'), $objects);
*
* @template T
*
* @param callable(T):bool $predicate Predicate function
* @param iterable<T> $iterable Iterable to filter
*
* @return \Iterator<T>
*/
function filter(callable $predicate, iterable $iterable): \Iterator {
foreach ($iterable as $key => $value) {
if ($predicate($value)) {
yield $key => $value;
}
}
}
/**
* Alias of toPairs().
*
* @template TKey
* @template TValue
*
* @param iterable<TKey,TValue> $iterable Iterable to enumerate
*
* @return \Iterator<array{0:TKey, 1:TValue}>
*/
function enumerate(iterable $iterable): \Iterator {
return toPairs($iterable);
}
/**
* Converts an iterable of key => value into an iterable of [key, value] pairs.
*
* Examples:
*
* iter\toPairs(['a', 'b']);
* => iter([0, 'a'], [1, 'b'])
*
* $values = ['a', 'b', 'c', 'd'];
* $filter = function($t) { return $t[0] % 2 == 0; };
* iter\fromPairs(iter\filter($filter, iter\toPairs($values)));
* => iter('a', 'c')
*
* @template TKey
* @template TValue
*
* @param iterable<TKey,TValue> $iterable Iterable to convert to pairs
*
* @return \Iterator<array{0:TKey, 1:TValue}>
*/
function toPairs(iterable $iterable): \Iterator {
foreach ($iterable as $key => $value) {
yield [$key, $value];
}
}
/**
* Converts an iterable of [key, value] pairs into a key => value iterable.
*
* This acts as an inverse to the toPairs() function.
*
* Examples:
*
* iter\fromPairs([['a', 1], ['b', 2]])
* => iter('a' => 1, 'b' => 2)
*
* $map = ['a' => 1, 'b' => 2];
* iter\fromPairs(iter\toPairs($map))
* => iter('a' => 1, 'b' => 2)
*
* @template TKey
* @template TValue
*
* @param iterable<array{0:TKey, 1:TValue}> $iterable Iterable of [key, value] pairs
*
* @return \Iterator<TKey,TValue>
*/
function fromPairs(iterable $iterable): \Iterator {
foreach ($iterable as [$key, $value]) {
yield $key => $value;
}
}
/**
* Reduce iterable using a function.
*
* The reduction function is passed an accumulator value and the current
* iterator value and returns a new accumulator. The accumulator is initialized
* to $startValue.
*
* Examples:
*
* iter\reduce(iter\func\operator('+'), range(1, 5), 0)
* => 15
* iter\reduce(iter\func\operator('*'), range(1, 5), 1)
* => 120
*
* @template TKey
* @template TValue
* @template TAcc
*
* @param callable(TAcc,TValue,TKey):TAcc $function Reduction function
* @param iterable<TKey,TValue> $iterable Iterable to reduce
* @param TAcc $startValue Start value for accumulator.
* Usually identity value of $function.
*
* @return TAcc Result of the reduction
*/
function reduce(callable $function, iterable $iterable, $startValue = null) {
$acc = $startValue;
foreach ($iterable as $key => $value) {
$acc = $function($acc, $value, $key);
}
return $acc;
}
/**
* Intermediate values of reducing iterable using a function.
*
* The reduction function is passed an accumulator value and the current
* iterator value and returns a new accumulator. The accumulator is initialized
* to $startValue.
*
* Reductions yield each accumulator along the way.
*
* Examples:
*
* iter\reductions(iter\func\operator('+'), range(1, 5), 0)
* => iter(1, 3, 6, 10, 15)
* iter\reductions(iter\func\operator('*'), range(1, 5), 1)
* => iter(1, 2, 6, 24, 120)
*
* @template TKey
* @template TValue
* @template TAcc
*
* @param callable(TAcc,TValue,TKey):TAcc $function Reduction function
* @param iterable<TKey,TValue> $iterable Iterable to reduce
* @param TAcc $startValue Start value for accumulator.
* Usually identity value of $function.
*
* @return \Iterator<TAcc> Intermediate results of the reduction
*/
function reductions(callable $function, iterable $iterable, $startValue = null): \Iterator {
$acc = $startValue;
foreach ($iterable as $key => $value) {
$acc = $function($acc, $value, $key);
yield $acc;
}
}
/**
* Zips the iterables that were passed as arguments.
*
* Afterwards keys and values will be arrays containing the keys/values of
* the individual iterables. This function stops as soon as the first iterable
* becomes invalid.
*
* Examples:
*
* iter\zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
* => iter([1, 4, 7], [2, 5, 8], [3, 6, 9])
*
* @param iterable ...$iterables Iterables to zip
*
* @return \Iterator<array>
*/
function zip(iterable ...$iterables): \Iterator {
if (\count($iterables) === 0) {
return;
}
$iterators = array_map('iter\\toIter', $iterables);
for (
apply(func\method('rewind'), $iterators);
all(func\method('valid'), $iterators);
apply(func\method('next'), $iterators)
) {
yield toArray(map(func\method('key'), $iterators))
=> toArray(map(func\method('current'), $iterators));
}
}
/**
* Combines an iterable for keys and another for values into one iterator.
*
* Examples:
*
* iter\zipKeyValue(['a', 'b', 'c'], [1, 2, 3])
* => iter('a' => 1, 'b' => 2, 'c' => 3)
*
* @template TKey
* @template TValue
*
* @param iterable<TKey> $keys Iterable of keys
* @param iterable<TValue> $values Iterable of values
*
* @return \Iterator<TKey,TValue>
*/
function zipKeyValue(iterable $keys, iterable $values): \Iterator {
$keys = toIter($keys);
$values = toIter($values);
for (
$keys->rewind(), $values->rewind();
$keys->valid() && $values->valid();
$keys->next(), $values->next()
) {
yield $keys->current() => $values->current();
}
}
/**
* Chains the iterables that were passed as arguments.
*
* The resulting iterator will contain the values of the first iterable, then
* the second, and so on.
*
* Examples:
*
* iter\chain(iter\range(0, 5), iter\range(6, 10), iter\range(11, 15))
* => iter(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
*
* @template T
*
* @param iterable<T> ...$iterables Iterables to chain
*
* @return \Iterator<T>
*/
function chain(iterable ...$iterables): \Iterator {
foreach ($iterables as $iterable) {
yield from $iterable;
}
}
/**
* Returns the cartesian product of iterables that were passed as arguments.
*
* The resulting iterator will contain all the possible tuples of keys and
* values.
*
* Please note that the iterables after the first must be rewindable.
*
* Examples:
*
* iter\product(iter\range(1, 2), iter\rewindable\range(3, 4))
* => iter([1, 3], [1, 4], [2, 3], [2, 4])
*
* @param iterable ...$iterables Iterables to combine
*
* @return \Iterator<array>
*/
function product(iterable ...$iterables): \Iterator {
$iterators = array_map('iter\\toIter', $iterables);
$numIterators = \count($iterators);
if (!$numIterators) {
yield [] => [];
return;
}
$keyTuple = $valueTuple = array_fill(0, $numIterators, null);
$i = -1;
while (true) {
while (++$i < $numIterators - 1) {
$iterators[$i]->rewind();
if (!$iterators[$i]->valid()) {
return;
}
$keyTuple[$i] = $iterators[$i]->key();
$valueTuple[$i] = $iterators[$i]->current();
}
foreach ($iterators[$i] as $keyTuple[$i] => $valueTuple[$i]) {
yield $keyTuple => $valueTuple;
}
while (--$i >= 0) {
$iterators[$i]->next();
if ($iterators[$i]->valid()) {
$keyTuple[$i] = $iterators[$i]->key();
$valueTuple[$i] = $iterators[$i]->current();
continue 2;
}
}
return;
}
}
/**
* Takes a slice from an iterable.
*
* Examples:
*
* iter\slice([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5], 5)
* => iter(0, 1, 2, 3, 4, 5)
* iter\slice([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5], 5, 3)
* => iter(0, 1, 2, 3)
*
* @template T
*
* @param iterable<T> $iterable Iterable to take the slice from
* @param int $start Start offset
* @param int $length Length (if not specified all remaining values from the
* iterable are used)
*
* @return \Iterator<T>
*/
function slice(iterable $iterable, int $start, $length = PHP_INT_MAX): \Iterator {
if ($start < 0) {
throw new \InvalidArgumentException('Start offset must be non-negative');
}
if ($length < 0) {
throw new \InvalidArgumentException('Length must be non-negative');
}
if ($length === 0) {
return;
}
$i = 0;
foreach ($iterable as $key => $value) {
if ($i++ < $start) {
continue;
}
yield $key => $value;
if ($i >= $start + $length) {
break;
}
}
}
/**
* Takes the first n items from an iterable.
*
* Examples:
*
* iter\take(3, [1, 2, 3, 4, 5])
* => iter(1, 2, 3)
*
* @template T
*
* @param int $num Number of elements to take from the start
* @param iterable<T> $iterable Iterable to take the elements from
*
* @return \Iterator<T>
*/
function take(int $num, iterable $iterable): \Iterator {
return slice($iterable, 0, $num);
}
/**
* Drops the first n items from an iterable.
*
* Examples:
*
* iter\drop(3, [1, 2, 3, 4, 5])
* => iter(4, 5)
*
* @template T
*
* @param int $num Number of elements to drop from the start
* @param iterable<T> $iterable Iterable to drop the elements from
*
* @return \Iterator<T>
*/
function drop(int $num, iterable $iterable): \Iterator {
return slice($iterable, $num);
}
/**
* Repeat an element a given number of times. By default the element is repeated
* indefinitely.
*
* Examples:
*
* iter\repeat(42, 5)
* => iter(42, 42, 42, 42, 42)
* iter\repeat(1)
* => iter(1, 1, 1, 1, 1, 1, 1, 1, 1, ...)
*
* @template T
*
* @param T $value Value to repeat
* @param int $num Number of repetitions (defaults to PHP_INT_MAX)
*
* @throws \InvalidArgumentException if num is negative
*
* @return \Iterator<T>
*/
function repeat($value, $num = PHP_INT_MAX): \Iterator {
if ($num < 0) {
throw new \InvalidArgumentException(
'Number of repetitions must be non-negative');
}
for ($i = 0; $i < $num; ++$i) {
yield $value;
}
}
/**
* Returns the keys of an iterable.
*
* Examples:
*
* iter\keys(['a' => 0, 'b' => 1, 'c' => 2])
* => iter('a', 'b', 'c')
*
* @template TKey
* @template TValue
*
* @param iterable<TKey,TValue> $iterable Iterable to get keys from
*
* @return \Iterator<TKey>
*/
function keys(iterable $iterable): \Iterator {
foreach ($iterable as $key => $_) {
yield $key;
}
}
/**
* Returns the values of an iterable, making the keys continuously indexed.
*
* Examples:
*
* iter\values([17 => 1, 42 => 2, -2 => 100])
* => iter(0 => 1, 1 => 42, 2 => 100)
*
* @template T
*
* @param iterable<T> $iterable Iterable to get values from
*
* @return \Iterator<T>
*/
function values(iterable $iterable): \Iterator {
foreach ($iterable as $value) {
yield $value;
}
}
/**
* Returns true if there is a value in the iterable that satisfies the
* predicate.
*
* This function is short-circuiting, i.e. if the predicate matches for any one
* element the remaining elements will not be considered anymore.
*
* Examples:
*
* iter\all(iter\func\operator('>', 0), range(1, 10))
* => true
* iter\all(iter\func\operator('>', 0), range(-5, 5))
* => false
*
* @template T
*
* @param callable(T):bool $predicate Predicate function
* @param iterable<T> $iterable Iterable to check against the predicate
*
* @return bool Whether the predicate matches any value
*/
function any(callable $predicate, iterable $iterable): bool {
foreach ($iterable as $value) {
if ($predicate($value)) {
return true;
}
}
return false;
}
/**
* Returns true if all values in the iterable satisfy the predicate.
*
* This function is short-circuiting, i.e. if the predicate fails for one
* element the remaining elements will not be considered anymore.
*
* Examples:
*
* iter\all(iter\func\operator('>', 0), range(1, 10))
* => true
* iter\all(iter\func\operator('>', 0), range(-5, 5))
* => false
*
* @template T
*
* @param callable(T):bool $predicate Predicate function
* @param iterable<T> $iterable Iterable to check against the predicate
*
* @return bool Whether the predicate holds for all values
*/
function all(callable $predicate, iterable $iterable): bool {
foreach ($iterable as $value) {
if (!$predicate($value)) {
return false;
}
}
return true;
}
/**
* Searches an iterable until a predicate returns true, then returns
* the value of the matching element.
*
* Examples:
*
* iter\search(iter\func\operator('===', 'baz'), ['foo', 'bar', 'baz'])
* => 'baz'
*
* iter\search(iter\func\operator('===', 'qux'), ['foo', 'bar', 'baz'])
* => null
*
* @template T
*
* @param callable(T):bool $predicate Predicate function
* @param iterable<T> $iterable The iterable to search
*
* @return T|null
*/
function search(callable $predicate, iterable $iterable) {
foreach ($iterable as $value) {
if ($predicate($value)) {
return $value;
}
}
return null;
}
/**
* Takes items from an iterable until the predicate fails for the first time.
*
* This means that all elements before (and excluding) the first element on
* which the predicate fails will be returned.
*
* Examples:
*
* iter\takeWhile(iter\func\operator('>', 0), [3, 1, 4, -1, 5])
* => iter(3, 1, 4)
*
* @template T
*
* @param callable(T):bool $predicate Predicate function
* @param iterable<T> $iterable Iterable to take values from
*
* @return \Iterator<T>
*/
function takeWhile(callable $predicate, iterable $iterable): \Iterator {
foreach ($iterable as $key => $value) {
if (!$predicate($value)) {
return;
}
yield $key => $value;
}
}
/**
* Drops items from an iterable until the predicate fails for the first time.
*
* This means that all elements after (and including) the first element on
* which the predicate fails will be returned.
*
* Examples:
*
* iter\dropWhile(iter\func\operator('>', 0), [3, 1, 4, -1, 5])
* => iter(-1, 5)
*
* @template T
*
* @param callable(T):bool $predicate Predicate function
* @param iterable<T> $iterable Iterable to drop values from
*
* @return \Iterator<T>
*/
function dropWhile(callable $predicate, iterable $iterable): \Iterator {
$failed = false;
foreach ($iterable as $key => $value) {
if (!$failed && !$predicate($value)) {
$failed = true;
}
if ($failed) {
yield $key => $value;
}
}
}
/**
* Takes an iterable containing any amount of nested iterables and returns
* a flat iterable with just the values.
*
* The $level argument allows to limit flattening to a certain number of levels.
*
* Examples:
*
* iter\flatten([1, [2, [3, 4]], [5]])
* => iter(1, 2, 3, 4, 5)
* iter\flatten([1, [2, [3, 4]], [5]], 1)
* => iter(1, 2, [3, 4], 5)
*
* @param iterable $iterable Iterable to flatten
* @param int $levels Number of levels to flatten
*
* @return \Iterator
*
* Note: Psalm does not support recursive type definitions yet, so it is not
* currently possible to correctly provide generic type information for
* this function.
* @see https://github.com/vimeo/psalm/issues/2777
* @see https://github.com/vimeo/psalm/issues/5739
*/
function flatten(iterable $iterable, $levels = PHP_INT_MAX): \Iterator {
if ($levels < 0) {
throw new \InvalidArgumentException(
'Number of levels must be non-negative'
);
}
if ($levels === 0) {
// Flatten zero levels == do nothing
yield from $iterable;
} else if ($levels === 1) {
// Optimized implementation for flattening one level
foreach ($iterable as $key => $value) {
if (isIterable($value)) {
yield from $value;
} else {
yield $key => $value;
}
}
} else {
// Otherwise flatten recursively
foreach ($iterable as $key => $value) {
if (isIterable($value)) {
yield from flatten($value, $levels - 1);
} else {
yield $key => $value;
}
}
}
}
/**
* Flips the keys and values of an iterable.
*
* Examples:
*
* iter\flip(['a' => 1, 'b' => 2, 'c' => 3])
* => iter(1 => 'a', 2 => 'b', 3 => 'c')
*
* @template TKey
* @template TValue
*
* @param iterable<TKey,TValue> $iterable The iterable to flip
*
* @return \Iterator<TValue,TKey>
*/
function flip(iterable $iterable): \Iterator {
foreach ($iterable as $key => $value) {
yield $value => $key;
}
}
/**
* Chunks an iterable into arrays of the specified size.
*
* Each chunk is an array (non-lazy), but the chunks are yielded lazily.
* By default keys are not preserved.
*
* Examples:
*
* iter\chunk([1, 2, 3, 4, 5], 2)
* => iter([1, 2], [3, 4], [5])
*
* @template TKey
* @template TValue
* @template TPreserveKeys of bool
*
* @param iterable<TKey,TValue> $iterable The iterable to chunk
* @param int $size The size of each chunk
* @param TPreserveKeys $preserveKeys Whether to preserve keys from the input iterable
*
* @return (
* TPreserveKeys is true
* ? \Iterator<array<TKey,TValue>>
* : \Iterator<array<array-key,TValue>>
* ) An iterator of arrays
*/
function chunk(iterable $iterable, int $size, bool $preserveKeys = false): \Iterator {
if ($size <= 0) {
throw new \InvalidArgumentException('Chunk size must be positive');
}
$chunk = [];
$count = 0;
foreach ($iterable as $key => $value) {
if ($preserveKeys) {
$chunk[$key] = $value;
} else {
$chunk[] = $value;
}
$count++;
if ($count === $size) {
yield $chunk;
$count = 0;
$chunk = [];
}
}
if ($count !== 0) {
yield $chunk;
}
}
/**
* The same as chunk(), but preserving keys.
*
* Examples:
*
* iter\chunkWithKeys(['a' => 1, 'b' => 2, 'c' => 3], 2)
* => iter(['a' => 1, 'b' => 2], ['c' => 3])
*
* @template TKey
* @template TValue
*
* @param iterable<TKey,TValue> $iterable The iterable to chunk
* @param int $size The size of each chunk
*
* @return \Iterator<array<TKey,TValue>> An iterator of arrays
*/
function chunkWithKeys(iterable $iterable, int $size): \Iterator {
return chunk($iterable, $size, true);
}
/**
* Joins the elements of an iterable with a separator between them.
*
* Examples:
*
* iter\join(', ', ['a', 'b', 'c'])
* => "a, b, c"
*
* @param string $separator Separator to use between elements
* @param iterable<string|\Stringable> $iterable The iterable to join
*
* @return string
*/
function join(string $separator, iterable $iterable): string {
$str = '';
$first = true;
foreach ($iterable as $value) {
if ($first) {
$str .= $value;
$first = false;