Skip to content

Instantly share code, notes, and snippets.

@OzanKurt
Forked from adamwathan/maxBy.php
Created August 15, 2020 03:30
Show Gist options
  • Save OzanKurt/d3dc864fd1ee66f0bb03ff6c1cd3f8b6 to your computer and use it in GitHub Desktop.
Save OzanKurt/d3dc864fd1ee66f0bb03ff6c1cd3f8b6 to your computer and use it in GitHub Desktop.
maxBy/minBy macros
<?php
Collection::macro('maxBy', function ($callback) {
$callback = $this->valueRetriever($callback);
return $this->reduce(function ($result, $item) use ($callback) {
if ($result === null) {
return $item;
}
return $callback($item) > $callback($result) ? $item : $result;
});
});
<?php
Collection::macro('minBy', function ($callback) {
$callback = $this->valueRetriever($callback);
return $this->reduce(function ($result, $item) use ($callback) {
if ($result === null) {
return $item;
}
return $callback($item) < $callback($result) ? $item : $result;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment