Skip to content

Commit

Permalink
refactor: Update Reverse operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Sep 21, 2020
1 parent 1183407 commit 6ce7b13
Showing 1 changed file with 31 additions and 6 deletions.
37 changes: 31 additions & 6 deletions src/Operation/Reverse.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace loophp\collection\Operation;

use ArrayIterator;
use Closure;
use Generator;
use Iterator;
Expand All @@ -12,6 +13,8 @@
* @psalm-template TKey
* @psalm-template TKey of array-key
* @psalm-template T
*
* phpcs:disable Generic.WhiteSpace.ScopeIndent.IncorrectExact
*/
final class Reverse extends AbstractOperation
{
Expand All @@ -27,15 +30,37 @@ public function __invoke(): Closure
* @psalm-return Generator<TKey, T, mixed, void>
*/
static function (Iterator $iterator): Generator {
/** @psalm-var Generator<int, array{0: TKey, 1: T}> $pack */
$pack = Pack::of()($iterator);
$all = iterator_to_array($pack);
/** @psalm-var Generator<int, array{0: TKey, 1: T}> $iterator */
$iterator = Pack::of()($iterator);
/** @psalm-var Generator<int, array{0: array{0: TKey, 1: T}}> $iterator */
$iterator = Wrap::of()($iterator);

for (end($all); null !== key($all); prev($all)) {
$item = current($all);
/**
* @param array $carry
* @psalm-param array<int, array{0: TKey, 1: T}> $carry
*
* @param array $value
* @psalm-param array{0: TKey, 1: T} $value
*
* @psalm-return array<int, array{0: TKey, 1: T}>
*/
$callback = static function (array $carry, array $value): array {
array_unshift($carry, ...$value);

yield $item[0] => $item[1];
return $carry;
};

if (!$iterator->valid()) {
return yield from [];
}

/** @psalm-var Iterator<int, array{0: TKey, 1: T}> $foldLeft1 */
$foldLeft1 = FoldLeft1::of()($callback)($iterator);

/** @psalm-var Iterator<TKey, T> $unpack */
$unpack = Unpack::of()(new ArrayIterator($foldLeft1->current()));

return yield from $unpack;
};
}
}

0 comments on commit 6ce7b13

Please sign in to comment.