Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/ds.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function mapFromEntries(iterable $entries): Map

/**
* @param iterable<K, V> $iterable
* @param callable(K, V): Pair<KReturn, VReturn> $mapper
* @param callable(K, V): Pair<KReturn, VReturn>|null $mapper If not provided then the output for `iterable<K, V>` is `Map<K, V>`
*
* @return Map<KReturn, VReturn>
*
Expand All @@ -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<KReturn, VReturn> $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);
Expand Down
16 changes: 16 additions & 0 deletions tests/DsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,22 @@ public function testMapFromIterable(): void
self::assertFalse($map->get(4));
}

public function testMapFromIterableNoopMapper(): void
{
/** @var callable():Generator<int, bool> $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<int, string> $iterableFactory */
Expand Down