| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Improved; |
||
| 6 | |||
| 7 | /** |
||
| 8 | * Get the maximal element according to a given comparator. |
||
| 9 | * |
||
| 10 | * @param iterable $iterable |
||
| 11 | * @param callable|null $compare |
||
| 12 | * @return mixed |
||
| 13 | */ |
||
| 14 | function iterable_max(iterable $iterable, callable $compare = null) |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 15 | { |
||
| 16 | 26 | $first = true; |
|
| 17 | 26 | $max = null; |
|
| 18 | |||
| 19 | 26 | if (!isset($compare)) { |
|
| 20 | 19 | foreach ($iterable as $value) { |
|
| 21 | 18 | $max = (!isset($max) || $value > $max) ? $value : $max; |
|
| 22 | } |
||
| 23 | } else { |
||
| 24 | 7 | foreach ($iterable as $value) { |
|
| 25 | 7 | $max = ($first || call_user_func($compare, $max, $value) < 0) ? $value : $max; |
|
| 26 | 7 | $first = false; |
|
| 27 | } |
||
| 28 | } |
||
| 29 | |||
| 30 | 26 | return $max; |
|
| 31 | } |
||
| 32 |