1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Improved; |
||
6 | |||
7 | /** |
||
8 | * Get a limited subset of the elements using an offset and (optionally) a limit. |
||
9 | * |
||
10 | * @param iterable $iterable |
||
11 | * @param int $offset |
||
12 | * @param int|null $limit |
||
13 | * @return \Generator |
||
14 | */ |
||
15 | 16 | function iterable_slice(iterable $iterable, int $offset, ?int $limit = null): \Generator |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
16 | { |
||
17 | 16 | $counter = 0; |
|
18 | 16 | $end = isset($limit) ? ($offset + $limit) : PHP_INT_MAX; |
|
19 | |||
20 | 16 | foreach ($iterable as $key => $value) { |
|
21 | 15 | if ($counter === $end) { |
|
22 | 10 | return; |
|
23 | } |
||
24 | |||
25 | 15 | if ($counter >= $offset) { |
|
26 | 15 | yield $key => $value; |
|
27 | } |
||
28 | |||
29 | 15 | $counter++; |
|
30 | } |
||
31 | } |
||
32 |