| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Improved; |
||
| 6 | |||
| 7 | /** |
||
| 8 | * Group elements of an array or iterator. |
||
| 9 | * |
||
| 10 | * @param iterable $iterable |
||
| 11 | * @param callable $grouping |
||
| 12 | * @return \Generator |
||
| 13 | */ |
||
| 14 | 9 | function iterable_group(iterable $iterable, callable $grouping): \Generator |
|
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 15 | { |
||
| 16 | 8 | $groups = []; |
|
| 17 | 8 | $values = []; |
|
| 18 | |||
| 19 | 8 | foreach ($iterable as $key => $value) { |
|
| 20 | 7 | $group = call_user_func($grouping, $value, $key); |
|
| 21 | |||
| 22 | 7 | $index = array_search($group, $groups, true); |
|
| 23 | |||
| 24 | 7 | if ($index === false) { |
|
| 25 | 7 | $index = array_push($groups, $group) - 1; |
|
| 26 | } |
||
| 27 | |||
| 28 | 7 | $values[$index][] = $value; |
|
| 29 | } |
||
| 30 | |||
| 31 | 8 | unset($iterable); |
|
| 32 | |||
| 33 | 8 | foreach ($groups as $index => $group) { |
|
| 34 | 7 | yield $group => $values[$index]; |
|
| 35 | } |
||
| 36 | } |
||
| 37 |