From d73e9f2181a133b18cf9bb0bd0ad381c00974897 Mon Sep 17 00:00:00 2001 From: whsv26 Date: Wed, 22 Dec 2021 00:43:54 +0300 Subject: [PATCH] [Collection] Stream toAssocArray cast. --- src/Fp/Streams/Stream.php | 19 +++++++++++++++++++ src/Fp/Streams/StreamCastableOps.php | 13 +++++++++++++ tests/Runtime/Classes/Stream/StreamTest.php | 5 +++++ 3 files changed, 37 insertions(+) diff --git a/src/Fp/Streams/Stream.php b/src/Fp/Streams/Stream.php index 67f518fe..c34cf165 100644 --- a/src/Fp/Streams/Stream.php +++ b/src/Fp/Streams/Stream.php @@ -52,6 +52,7 @@ use SplFileObject; use function Fp\Callable\asGenerator; +use function Fp\Cast\asArray; use function Fp\Cast\asList; /** @@ -622,6 +623,24 @@ public function toArray(): array return $this->leaf(asList($this->emitter)); } + /** + * @inheritDoc + * @template TKO of array-key + * @template TVO + * @param callable(TV): array{TKO, TVO} $callback + * @return array + */ + public function toAssocArray(callable $callback): array + { + /** @psalm-suppress ImpureFunctionCall */ + return $this->leaf(asArray(asGenerator(function () use ($callback) { + foreach ($this->emitter as $val) { + $pair = $callback($val); + yield $pair[0] => $pair[1]; + } + }))); + } + /** * @inheritDoc * @return LinkedList diff --git a/src/Fp/Streams/StreamCastableOps.php b/src/Fp/Streams/StreamCastableOps.php index 730f50a4..3eb474eb 100644 --- a/src/Fp/Streams/StreamCastableOps.php +++ b/src/Fp/Streams/StreamCastableOps.php @@ -27,6 +27,19 @@ interface StreamCastableOps */ public function toArray(): array; + /** + * ```php + * >>> Stream::emits([[1, 'a'], [2, 'b']])->toAssocArray(fn($pair) => $pair); + * => [1 => 'a', 2 => 'b'] + * ``` + * + * @template TKO of array-key + * @template TVO + * @param callable(TV): array{TKO, TVO} $callback + * @return array + */ + public function toAssocArray(callable $callback): array; + /** * ```php * >>> Stream::emits([1, 2, 2])->toLinkedList(); diff --git a/tests/Runtime/Classes/Stream/StreamTest.php b/tests/Runtime/Classes/Stream/StreamTest.php index d1558737..7fa354bf 100644 --- a/tests/Runtime/Classes/Stream/StreamTest.php +++ b/tests/Runtime/Classes/Stream/StreamTest.php @@ -38,5 +38,10 @@ public function testCasts(): void $this->assertEquals([[0, 0], [1, 1]], Stream::emits([0, 1])->toHashMap(fn($e) => [$e, $e])->toArray()); $this->assertInstanceOf(Some::class, Option::try(fn() => Stream::emits([0, 1])->toFile('/dev/null', false))); $this->assertInstanceOf(Some::class, Option::try(fn() => Stream::emits([0, 1])->toFile('/dev/null', true))); + + $this->assertEquals( + [1 => 'a', 2 => 'b'], + Stream::emits([[1, 'a'], [2, 'b']])->toAssocArray(fn($pair) => $pair) + ); } }