Skip to content

Commit

Permalink
Update Map operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Aug 21, 2020
1 parent 6496559 commit 8b1dd27
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/Operation/Map.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@

namespace loophp\collection\Operation;

use ArrayIterator;
use Closure;
use Generator;
use Iterator;
use loophp\collection\Contract\Operation;
use loophp\collection\Transformation\FoldLeft;
use loophp\collection\Transformation\Transform;

/**
* @psalm-template TKey
Expand All @@ -18,7 +21,7 @@ final class Map extends AbstractOperation implements Operation
{
public function __construct(callable ...$callbacks)
{
$this->storage['callbacks'] = $callbacks;
$this->storage['callbacks'] = new ArrayIterator($callbacks);
}

public function __invoke(): Closure
Expand All @@ -30,14 +33,13 @@ public function __invoke(): Closure
*
* @psalm-return \Generator<TKey, T>
*/
static function (Iterator $iterator, array $callbacks): Generator {
static function (Iterator $iterator, ArrayIterator $callbacks): Generator {
foreach ($iterator as $key => $value) {
// Custom array_reduce function with the key passed in argument.
foreach ($callbacks as $callback) {
$value = $callback($value, $key);
}
$callback = static function ($carry, callable $callback) use ($value, $key) {
return $callback($value, $key);
};

yield $key => $value;
yield $key => (new Transform(new FoldLeft($callback, $value)))($callbacks);
}
};
}
Expand Down

0 comments on commit 8b1dd27

Please sign in to comment.