Skip to content

Commit

Permalink
[Collection] Stream toAssocArray cast.
Browse files Browse the repository at this point in the history
  • Loading branch information
whsv26 committed Dec 21, 2021
1 parent 58f516e commit d73e9f2
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Fp/Streams/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
use SplFileObject;

use function Fp\Callable\asGenerator;
use function Fp\Cast\asArray;
use function Fp\Cast\asList;

/**
Expand Down Expand Up @@ -622,6 +623,24 @@ public function toArray(): array
return $this->leaf(asList($this->emitter));
}

/**
* @inheritDoc
* @template TKO of array-key
* @template TVO
* @param callable(TV): array{TKO, TVO} $callback
* @return array<TKO, TVO>
*/
public function toAssocArray(callable $callback): array
{
/** @psalm-suppress ImpureFunctionCall */
return $this->leaf(asArray(asGenerator(function () use ($callback) {
foreach ($this->emitter as $val) {
$pair = $callback($val);
yield $pair[0] => $pair[1];
}
})));
}

/**
* @inheritDoc
* @return LinkedList<TV>
Expand Down
13 changes: 13 additions & 0 deletions src/Fp/Streams/StreamCastableOps.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ interface StreamCastableOps
*/
public function toArray(): array;

/**
* ```php
* >>> Stream::emits([[1, 'a'], [2, 'b']])->toAssocArray(fn($pair) => $pair);
* => [1 => 'a', 2 => 'b']
* ```
*
* @template TKO of array-key
* @template TVO
* @param callable(TV): array{TKO, TVO} $callback
* @return array<TKO, TVO>
*/
public function toAssocArray(callable $callback): array;

/**
* ```php
* >>> Stream::emits([1, 2, 2])->toLinkedList();
Expand Down
5 changes: 5 additions & 0 deletions tests/Runtime/Classes/Stream/StreamTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,10 @@ public function testCasts(): void
$this->assertEquals([[0, 0], [1, 1]], Stream::emits([0, 1])->toHashMap(fn($e) => [$e, $e])->toArray());
$this->assertInstanceOf(Some::class, Option::try(fn() => Stream::emits([0, 1])->toFile('/dev/null', false)));
$this->assertInstanceOf(Some::class, Option::try(fn() => Stream::emits([0, 1])->toFile('/dev/null', true)));

$this->assertEquals(
[1 => 'a', 2 => 'b'],
Stream::emits([[1, 'a'], [2, 'b']])->toAssocArray(fn($pair) => $pair)
);
}
}

0 comments on commit d73e9f2

Please sign in to comment.