Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Created June 23, 2016 18:44
Show Gist options
  • Save adamwathan/78aa40a1abffbe7ce3c83b7b777312d4 to your computer and use it in GitHub Desktop.
Save adamwathan/78aa40a1abffbe7ce3c83b7b777312d4 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