From c9c8bc6b42bb83727e0653acf74ba1e516c120d5 Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Mon, 12 Jun 2023 13:02:44 +0300 Subject: [PATCH] feat: allow noop mapper for `mapFromIterable` --- src/ds.php | 6 ++++-- tests/DsTest.php | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/ds.php b/src/ds.php index ac9885c..9a58698 100644 --- a/src/ds.php +++ b/src/ds.php @@ -31,7 +31,7 @@ function mapFromEntries(iterable $entries): Map /** * @param iterable $iterable - * @param callable(K, V): Pair $mapper + * @param callable(K, V): Pair|null $mapper If not provided then the output for `iterable` is `Map` * * @return Map * @@ -40,11 +40,13 @@ function mapFromEntries(iterable $entries): Map * @template KReturn * @template VReturn */ -function mapFromIterable(iterable $iterable, callable $mapper): Map +function mapFromIterable(iterable $iterable, callable|null $mapper = null): Map { /** @var Map $map */ $map = new Map(); + $mapper ??= static fn ($key, $value) => new Pair($key, $value); + foreach ($iterable as $key => $value) { $keyValue = $mapper($key, $value); $map->put($keyValue->key, $keyValue->value); diff --git a/tests/DsTest.php b/tests/DsTest.php index b5602a6..b20d688 100644 --- a/tests/DsTest.php +++ b/tests/DsTest.php @@ -53,6 +53,22 @@ public function testMapFromIterable(): void self::assertFalse($map->get(4)); } + public function testMapFromIterableNoopMapper(): void + { + /** @var callable():Generator $iterableFactory */ + $iterableFactory = static function (): Generator { + yield 1 => true; + yield 2 => false; + yield 2 => true; + }; + + $map = mapFromIterable($iterableFactory()); + + self::assertCount(2, $map); + self::assertTrue($map->get(1)); + self::assertTrue($map->get(2)); + } + public function testMappedValueSetsFromIterable(): void { /** @var callable():Generator $iterableFactory */