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