Skip to content

Commit c9c8bc6

Browse files
committed
feat: allow noop mapper for mapFromIterable
1 parent b83e535 commit c9c8bc6

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/ds.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ function mapFromEntries(iterable $entries): Map
3131

3232
/**
3333
* @param iterable<K, V> $iterable
34-
* @param callable(K, V): Pair<KReturn, VReturn> $mapper
34+
* @param callable(K, V): Pair<KReturn, VReturn>|null $mapper If not provided then the output for `iterable<K, V>` is `Map<K, V>`
3535
*
3636
* @return Map<KReturn, VReturn>
3737
*
@@ -40,11 +40,13 @@ function mapFromEntries(iterable $entries): Map
4040
* @template KReturn
4141
* @template VReturn
4242
*/
43-
function mapFromIterable(iterable $iterable, callable $mapper): Map
43+
function mapFromIterable(iterable $iterable, callable|null $mapper = null): Map
4444
{
4545
/** @var Map<KReturn, VReturn> $map */
4646
$map = new Map();
4747

48+
$mapper ??= static fn ($key, $value) => new Pair($key, $value);
49+
4850
foreach ($iterable as $key => $value) {
4951
$keyValue = $mapper($key, $value);
5052
$map->put($keyValue->key, $keyValue->value);

tests/DsTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,22 @@ public function testMapFromIterable(): void
5353
self::assertFalse($map->get(4));
5454
}
5555

56+
public function testMapFromIterableNoopMapper(): void
57+
{
58+
/** @var callable():Generator<int, bool> $iterableFactory */
59+
$iterableFactory = static function (): Generator {
60+
yield 1 => true;
61+
yield 2 => false;
62+
yield 2 => true;
63+
};
64+
65+
$map = mapFromIterable($iterableFactory());
66+
67+
self::assertCount(2, $map);
68+
self::assertTrue($map->get(1));
69+
self::assertTrue($map->get(2));
70+
}
71+
5672
public function testMappedValueSetsFromIterable(): void
5773
{
5874
/** @var callable():Generator<int, string> $iterableFactory */

0 commit comments

Comments
 (0)