From 22a83322612900b634434facefeb5c1890826e95 Mon Sep 17 00:00:00 2001 From: Niklas Keller Date: Fri, 5 Oct 2018 21:01:57 +0200 Subject: [PATCH] Add Iterator\collect --- lib/functions.php | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lib/functions.php b/lib/functions.php index 24cc5eb..ffb025f 100644 --- a/lib/functions.php +++ b/lib/functions.php @@ -451,6 +451,7 @@ namespace Amp\Iterator use Amp\Iterator; use Amp\Producer; use Amp\Promise; + use function Amp\call; use function Amp\coroutine; use function Amp\Internal\createTypeError; @@ -616,4 +617,23 @@ namespace Amp\Iterator return $emitter->iterate(); } + + /** + * Collects all items from an iterator into an array. + * + * @param Iterator $iterator + * + * @return Promise + */ + function collect(Iterator $iterator): Promise + { + return call(function () use ($iterator) { + $array = []; + while (yield $iterator->advance()) { + $array[] = $iterator->getCurrent(); + } + + return $array; + }); + } }