Skip to content

Instantly share code, notes, and snippets.

@thinkstylestudio
Forked from adamwathan/maxBy.php
Created May 25, 2017 18:16
Show Gist options
  • Save thinkstylestudio/920e078ad703524576f5f2932fd63be6 to your computer and use it in GitHub Desktop.
Save thinkstylestudio/920e078ad703524576f5f2932fd63be6 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