Skip to content

Commit

Permalink
Add Amp\Iterator\discard (#315)
Browse files Browse the repository at this point in the history
  • Loading branch information
kelunik committed May 6, 2020
1 parent 1e58d53 commit e2c63c8
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,31 @@ function concat(array $iterators): 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.
*
Expand Down
20 changes: 20 additions & 0 deletions test/IteratorDiscardTest.php
Original file line number Diff line number Diff line change
@@ -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)));
}
}

0 comments on commit e2c63c8

Please sign in to comment.