From 5e33cfb2d8ef381076d03659c9812c8ce00d7293 Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Tue, 14 Nov 2023 13:06:55 +0100 Subject: [PATCH] feat: better name mappedSetsFromIterable - deprecated mappedValueSetsFromIterable --- src/ds.php | 33 +++++++++++++++++++++++++++++++++ tests/DsTest.php | 8 ++++---- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/src/ds.php b/src/ds.php index ac9885c..fd278e2 100644 --- a/src/ds.php +++ b/src/ds.php @@ -54,6 +54,8 @@ function mapFromIterable(iterable $iterable, callable $mapper): Map } /** + * @deprecated Use {@link mappedSetsFromIterable} instead + * * @param iterable $iterable * @param callable(K, V): Pair $mapper * @@ -84,6 +86,37 @@ function mappedValueSetsFromIterable(iterable $iterable, callable $mapper): Map return $map; } +/** + * @param iterable $iterable + * @param callable(K, V): Pair $mapper + * + * @return Map> + * + * @template K + * @template V + * @template KReturn + * @template VReturn + */ +function mappedSetsFromIterable(iterable $iterable, callable $mapper): Map +{ + /** @var Map> $map */ + $map = new Map(); + + foreach ($iterable as $key => $value) { + $keyValue = $mapper($key, $value); + $set = $map->get($keyValue->key, null); + if ($set === null) { + /** @var Set $set */ + $set = new Set(); + $map->put($keyValue->key, $set); + } + + $set->add($keyValue->value); + } + + return $map; +} + /** * @param iterable $iterable * @param callable(K,V): VReturn $mapper diff --git a/tests/DsTest.php b/tests/DsTest.php index b5602a6..2b9d32b 100644 --- a/tests/DsTest.php +++ b/tests/DsTest.php @@ -11,12 +11,12 @@ use function Cdn77\Functions\mapFromEntries; use function Cdn77\Functions\mapFromIterable; -use function Cdn77\Functions\mappedValueSetsFromIterable; +use function Cdn77\Functions\mappedSetsFromIterable; use function Cdn77\Functions\setFromIterable; use function Cdn77\Functions\vectorFromIterable; #[CoversFunction('Cdn77\Functions\mapFromIterable')] -#[CoversFunction('Cdn77\Functions\mappedValueSetsFromIterable')] +#[CoversFunction('Cdn77\Functions\mappedSetsFromIterable')] #[CoversFunction('Cdn77\Functions\setFromIterable')] #[CoversFunction('Cdn77\Functions\vectorFromIterable')] final class DsTest extends TestCase @@ -53,7 +53,7 @@ public function testMapFromIterable(): void self::assertFalse($map->get(4)); } - public function testMappedValueSetsFromIterable(): void + public function testMappedSetsFromIterable(): void { /** @var callable():Generator $iterableFactory */ $iterableFactory = static function (): Generator { @@ -63,7 +63,7 @@ public function testMappedValueSetsFromIterable(): void yield 2 => 'b'; }; - $map = mappedValueSetsFromIterable( + $map = mappedSetsFromIterable( $iterableFactory(), static fn (int $key, string $value) => new Pair($key * 2, $value . '_') );