diff --git a/lib/functions.php b/lib/functions.php index 6e9e8ed..dab4f21 100644 --- a/lib/functions.php +++ b/lib/functions.php @@ -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 $iterator + * @psalm-return Promise + */ + 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. * diff --git a/test/IteratorDiscardTest.php b/test/IteratorDiscardTest.php new file mode 100644 index 0000000..4eb2fd7 --- /dev/null +++ b/test/IteratorDiscardTest.php @@ -0,0 +1,20 @@ +assertSame(0, yield discard(Iterator\fromIterable([]))); + } + + public function testCount(): \Generator + { + $this->assertSame(3, yield discard(Iterator\fromIterable(['a', 1, false], 1))); + } +}