1
0
mirror of https://github.com/danog/amp.git synced 2024-12-03 09:57:51 +01:00

Add Amp\Iterator\discard (#315)

This commit is contained in:
Niklas Keller 2020-05-06 18:57:29 +02:00 committed by GitHub
parent 1e58d53e4a
commit e2c63c83eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 0 deletions

View File

@ -762,6 +762,31 @@ namespace Amp\Iterator
return $emitter->iterate();
}
/**
* Discards all remaining items and returns the number of discarded items.
*
* @template TValue
*
* @param Iterator $iterator
*
* @return Promise
*
* @psalm-param Iterator<TValue> $iterator
* @psalm-return Promise<int>
*/
function discard(Iterator $iterator): Promise
{
return call(static function () use ($iterator): \Generator {
$count = 0;
while (yield $iterator->advance()) {
$count++;
}
return $count;
});
}
/**
* Collects all items from an iterator into an array.
*

View File

@ -0,0 +1,20 @@
<?php
namespace Amp\Test;
use Amp\Iterator;
use Amp\PHPUnit\AsyncTestCase;
use function Amp\Iterator\discard;
class IteratorDiscardTest extends AsyncTestCase
{
public function testEmpty(): \Generator
{
$this->assertSame(0, yield discard(Iterator\fromIterable([])));
}
public function testCount(): \Generator
{
$this->assertSame(3, yield discard(Iterator\fromIterable(['a', 1, false], 1)));
}
}