Skip to content

Commit d73e9f2

Browse files
committed
[Collection] Stream toAssocArray cast.
1 parent 58f516e commit d73e9f2

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

src/Fp/Streams/Stream.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
use SplFileObject;
5353

5454
use function Fp\Callable\asGenerator;
55+
use function Fp\Cast\asArray;
5556
use function Fp\Cast\asList;
5657

5758
/**
@@ -622,6 +623,24 @@ public function toArray(): array
622623
return $this->leaf(asList($this->emitter));
623624
}
624625

626+
/**
627+
* @inheritDoc
628+
* @template TKO of array-key
629+
* @template TVO
630+
* @param callable(TV): array{TKO, TVO} $callback
631+
* @return array<TKO, TVO>
632+
*/
633+
public function toAssocArray(callable $callback): array
634+
{
635+
/** @psalm-suppress ImpureFunctionCall */
636+
return $this->leaf(asArray(asGenerator(function () use ($callback) {
637+
foreach ($this->emitter as $val) {
638+
$pair = $callback($val);
639+
yield $pair[0] => $pair[1];
640+
}
641+
})));
642+
}
643+
625644
/**
626645
* @inheritDoc
627646
* @return LinkedList<TV>

src/Fp/Streams/StreamCastableOps.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,19 @@ interface StreamCastableOps
2727
*/
2828
public function toArray(): array;
2929

30+
/**
31+
* ```php
32+
* >>> Stream::emits([[1, 'a'], [2, 'b']])->toAssocArray(fn($pair) => $pair);
33+
* => [1 => 'a', 2 => 'b']
34+
* ```
35+
*
36+
* @template TKO of array-key
37+
* @template TVO
38+
* @param callable(TV): array{TKO, TVO} $callback
39+
* @return array<TKO, TVO>
40+
*/
41+
public function toAssocArray(callable $callback): array;
42+
3043
/**
3144
* ```php
3245
* >>> Stream::emits([1, 2, 2])->toLinkedList();

tests/Runtime/Classes/Stream/StreamTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,5 +38,10 @@ public function testCasts(): void
3838
$this->assertEquals([[0, 0], [1, 1]], Stream::emits([0, 1])->toHashMap(fn($e) => [$e, $e])->toArray());
3939
$this->assertInstanceOf(Some::class, Option::try(fn() => Stream::emits([0, 1])->toFile('/dev/null', false)));
4040
$this->assertInstanceOf(Some::class, Option::try(fn() => Stream::emits([0, 1])->toFile('/dev/null', true)));
41+
42+
$this->assertEquals(
43+
[1 => 'a', 2 => 'b'],
44+
Stream::emits([[1, 'a'], [2, 'b']])->toAssocArray(fn($pair) => $pair)
45+
);
4146
}
4247
}

0 commit comments

Comments
 (0)