Skip to content

Commit

Permalink
refactor: Tails operation, performance improvements
Browse files Browse the repository at this point in the history
Also make sure it retains the key.

BREAKING CHANGE: yes
  • Loading branch information
drupol committed Dec 6, 2022
1 parent 1c28be3 commit d71b2ef
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 15 deletions.
12 changes: 4 additions & 8 deletions src/Operation/Tails.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Closure;
use Generator;
use loophp\iterators\ConcatIterableAggregate;
use loophp\iterators\NormalizeIterableAggregate;
use loophp\iterators\ReductionIterableAggregate;

use function array_slice;
Expand All @@ -31,15 +32,10 @@ public function __invoke(): Closure
* @return Generator<int, list<T>>
*/
static function (iterable $iterable): Generator {
$iterator = new ConcatIterableAggregate([
[0 => 0],
$iterable,
]);

/** @var array<array-key, T> $generator */
$generator = iterator_to_array((new Normalize())()($iterator));
$generator = iterator_to_array(new ConcatIterableAggregate([[0 => 0], $iterable]));

yield from new ReductionIterableAggregate(
yield from new NormalizeIterableAggregate(new ReductionIterableAggregate(
$generator,
/**
* @param list<T> $stack
Expand All @@ -48,7 +44,7 @@ static function (iterable $iterable): Generator {
*/
static fn (array $stack): array => array_slice($stack, 1),
$generator
);
));
};
}
}
14 changes: 7 additions & 7 deletions tests/unit/Traits/GenericCollectionProviders.php
Original file line number Diff line number Diff line change
Expand Up @@ -3973,19 +3973,19 @@ public function tailOperationProvider()
public function tailsOperationProvider()
{
$operation = 'tails';
$input = range('A', 'E');
$input = array_combine(range('a', 'e'), range('A', 'E'));

yield [
$operation,
[],
$input,
[
['A', 'B', 'C', 'D', 'E'],
[0 => 'B', 1 => 'C', 2 => 'D', 3 => 'E'],
[0 => 'C', 1 => 'D', 2 => 'E'],
[0 => 'D', 1 => 'E'],
[0 => 'E'],
[],
0 => ['a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D', 'e' => 'E'],
1 => ['b' => 'B', 'c' => 'C', 'd' => 'D', 'e' => 'E'],
2 => ['c' => 'C', 'd' => 'D', 'e' => 'E'],
3 => ['d' => 'D', 'e' => 'E'],
4 => ['e' => 'E'],
5 => [],
],
];
}
Expand Down

0 comments on commit d71b2ef

Please sign in to comment.