| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Improved; |
||
| 6 | |||
| 7 | /** |
||
| 8 | * Reverse order of elements of an iterable. |
||
| 9 | * |
||
| 10 | * @param iterable $iterable |
||
| 11 | * @param bool $preserveKeys |
||
| 12 | * @return \Generator |
||
| 13 | */ |
||
| 14 | 15 | function iterable_reverse(iterable $iterable, bool $preserveKeys = false): \Generator |
|
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 15 | { |
||
| 16 | 14 | if (is_array($iterable)) { |
|
| 17 | 2 | $values = array_reverse($iterable, $preserveKeys); |
|
| 18 | 12 | } elseif (!$preserveKeys) { |
|
| 19 | 6 | $values = []; |
|
| 20 | |||
| 21 | 6 | foreach ($iterable as $key => $value) { |
|
| 22 | 5 | array_unshift($values, $value); |
|
| 23 | } |
||
| 24 | } else { |
||
| 25 | /** @var array $keys */ |
||
| 26 | 6 | $keys = []; |
|
|
0 ignored issues
–
show
|
|||
| 27 | 6 | $values = []; |
|
| 28 | |||
| 29 | 6 | foreach ($iterable as $key => $value) { |
|
| 30 | 5 | array_unshift($keys, $key); |
|
| 31 | 5 | array_unshift($values, $value); |
|
| 32 | } |
||
| 33 | } |
||
| 34 | |||
| 35 | 14 | unset($iterable); |
|
| 36 | |||
| 37 | 14 | foreach ($values as $index => $value) { |
|
| 38 | 12 | $key = isset($keys) ? $keys[$index] : $index; |
|
| 39 | 12 | yield $key => $value; |
|
| 40 | } |
||
| 41 | } |
||
| 42 |