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:
parent
1e58d53e4a
commit
e2c63c83eb
@ -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.
|
||||
*
|
||||
|
20
test/IteratorDiscardTest.php
Normal file
20
test/IteratorDiscardTest.php
Normal 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)));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user