Skip to content

Commit

Permalink
Update Map operation.
Browse files Browse the repository at this point in the history
Restore the use of variadic arguments, in the proper way.
  • Loading branch information
drupol committed Sep 3, 2020
1 parent 296aea1 commit 1521b23
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 5 deletions.
18 changes: 18 additions & 0 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -1247,6 +1247,24 @@ public function it_can_map(): void
return $item . $item;
})
->shouldIterateAs(['A' => 'AA', 'B' => 'BB', 'C' => 'CC', 'D' => 'DD', 'E' => 'EE']);

$callback1 = static function (string $a): string {
return $a . $a;
};

$callback2 = static function (string $a): string {
return '[' . $a . ']';
};

$this::fromIterable(range('a', 'e'))
->map($callback1, $callback2)
->shouldIterateAs([
'[aa]',
'[bb]',
'[cc]',
'[dd]',
'[ee]',
]);
}

public function it_can_merge(): void
Expand Down
35 changes: 30 additions & 5 deletions src/Operation/Map.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,50 @@
final class Map extends AbstractOperation
{
/**
* @psalm-return Closure(callable(T, TKey): T): Closure(Iterator<TKey, T>): Generator<TKey, T>
* @psalm-return Closure((callable(T, TKey): T)...): Closure(Iterator<TKey, T>): Generator<TKey, T>
*/
public function __invoke(): Closure
{
return
/**
* @psalm-param callable(T, TKey): T $callback
* @psalm-param callable(T, TKey): T ...$callbacks
*/
static function (callable $callback): Closure {
static function (callable ...$callbacks): Closure {
return
/**
* @psalm-param Iterator<TKey, T> $iterator
*
* @psalm-return Generator<TKey, T>
*/
static function (Iterator $iterator) use ($callback): Generator {
static function (Iterator $iterator) use ($callbacks): Generator {
$callbackFactory =
/**
* @psalm-param TKey $key
*
* @psalm-return Closure(T): Closure(T, callable(T, TKey): T): T
*
* @param mixed $key
*/
static function ($key): Closure {
return
/**
* @psalm-param T $carry
* @psalm-param callable(T, TKey): T $callback
*
* @psalm-return T
*
* @param mixed $carry
*/
static function ($carry, callable $callback) use ($key) {
return $callback($carry, $key);
};
};

// phpcs:disable
foreach ($iterator as $key => $value) {
yield $key => $callback($value, $key);
yield $key => array_reduce($callbacks, $callbackFactory($key), $value);
}
// phpcs:enable
};
};
}
Expand Down

0 comments on commit 1521b23

Please sign in to comment.