Skip to content

Instantly share code, notes, and snippets.

@cookavich
Forked from adamwathan/maxBy.php
Created August 17, 2017 18:10
Show Gist options
  • Save cookavich/f1fb4da9706676a8f7cd73d53d9518f4 to your computer and use it in GitHub Desktop.
Save cookavich/f1fb4da9706676a8f7cd73d53d9518f4 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