Skip to content

Instantly share code, notes, and snippets.

@texdc
Forked from mathiasverraes/max.php
Last active August 29, 2015 14:11
Show Gist options
  • Save texdc/675ff63cec3d190c39d0 to your computer and use it in GitHub Desktop.
Save texdc/675ff63cec3d190c39d0 to your computer and use it in GitHub Desktop.
<?php
// test data
class Foo
{
private $a;
public function __construct($a)
{
$this->a = (int) $a;
}
public function hasGreaterAThan(self $another)
{
return $this->a > $another->a;
}
}
$list = [
$foo1 = new Foo(2),
$foo2 = new Foo(5),
$foo3 = new Foo(1),
];
/**
* Finds an item in a list via a comparison function
*
* @param array $aList the collection to examine
* @param callable $comparison should compare two arguments and return a bool
* @return mixed
*/
$find_by = function(array $aList, callable $comparison) {
$callback = function($carry, $item) use ($comparison) {
return ($carry == null || $comparison($item, $carry)) ? $item : $carry;
};
return array_reduce($aList, $callback);
};
$greaterA = function(Foo $foo1, Foo $foo2) {
return $foo1->hasGreaterAThan($foo2);
};
$lesserA = function(Foo $foo1, Foo $foo2) {
return $foo2->hasGreaterAThan($foo1);
};
assert($find_by($list, $greaterA) === $foo2);
assert($find_by($list, $lesserA) === $foo3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment