1
0
mirror of https://github.com/danog/amp.git synced 2025-01-22 05:11:42 +01:00

functor argument is now optional in Amp\filter()

If no functor parameter is supplied, all results equal to FALSE
using a (bool) cast will be removed.
This commit is contained in:
Daniel Lowrey 2015-08-01 13:28:41 -04:00
parent 705c57483b
commit 2c8727133e
2 changed files with 23 additions and 3 deletions

View File

@ -511,11 +511,17 @@ function map(array $promises, callable $functor) {
* @param callable $functor The filtering function to apply to eventual promise results
* @return \Amp\Promise
*/
function filter(array $promises, callable $functor) {
function filter(array $promises, callable $functor = null) {
if (empty($promises)) {
return new Success([]);
}
if (empty($functor)) {
$functor = function ($r) {
return (bool) $r;
};
}
$struct = new \StdClass;
$struct->remaining = count($promises);
$struct->results = [];

View File

@ -204,6 +204,20 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase {
$this->assertSame([1=>"test2", 2=>"test2", 3=>"test2"], $result);
}
public function testFilterUsesBoolComparisonOnUnspecifiedFunctor() {
$promises = ["test1", new Success, null, false, 0, new Success("test2"), new Success(0), new Success(false) ];
$promise = \Amp\filter($promises);
$error = null;
$result = null;
$promise->when(function ($e, $r) use (&$error, &$result) {
$error = $e;
$result = $r;
});
$this->assertNull($error);
$this->assertSame([0=>"test1", 5=>"test2"], $result);
}
public function testFilter2() {
$promises = ["test1", "test2", new Success("test2"), new Success("test2")];
$functor = function ($el) { return $el === "test2"; };
@ -853,7 +867,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase {
\Amp\once(function () use ($promisor) {
$promisor->succeed(42);
}, 10);
$result = \Amp\wait($promisor->promise());
$this->assertSame(42, $result);
}
@ -869,7 +883,7 @@ class FunctionsTest extends \PHPUnit_Framework_TestCase {
"If the reader prefers, this code may be regarded as fiction"
));
}, 10);
\Amp\wait($promisor->promise());
}
}