Skip to content

Commit

Permalink
refactor: Tails operation, performance improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Dec 6, 2022
1 parent 486567a commit 1c28be3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
2 changes: 1 addition & 1 deletion phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ parameters:
path: src/Collection.php

-
message: "#^Parameter \\#1 \\$callable of class loophp\\\\collection\\\\Collection constructor expects callable\\(\\.\\.\\.mixed\\)\\: iterable\\<int, array\\<int, mixed\\>\\>, Closure\\(iterable\\)\\: Generator\\<int, array\\<int, mixed\\>, mixed, void\\> given\\.$#"
message: "#^Parameter \\#1 \\$callable of class loophp\\\\collection\\\\Collection constructor expects callable\\(\\.\\.\\.mixed\\)\\: iterable\\<int, array\\<int, mixed\\>\\>, Closure\\(iterable\\<\\(int\\|string\\), mixed\\>\\)\\: Generator\\<int, array\\<int, mixed\\>, mixed, mixed\\> given\\.$#"
count: 1
path: src/Collection.php

Expand Down
36 changes: 23 additions & 13 deletions src/Operation/Tails.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

use Closure;
use Generator;
use loophp\iterators\ConcatIterableAggregate;
use loophp\iterators\ReductionIterableAggregate;

use function array_slice;

/**
* @immutable
Expand All @@ -16,29 +20,35 @@
final class Tails extends AbstractOperation
{
/**
* @return Closure(iterable<TKey, T>): Generator<int, list<T>, mixed, void>
* @return Closure(iterable<array-key, T>): Generator<int, list<T>>
*/
public function __invoke(): Closure
{
return
/**
* @param iterable<TKey, T> $iterable
* @param iterable<array-key, T> $iterable
*
* @return Generator<int, list<T>, mixed, void>
* @return Generator<int, list<T>>
*/
static function (iterable $iterable): Generator {
/** @var Generator<int, array{0: TKey, 1: T}> $generator */
$generator = (new Pack())()($iterable);
$data = [...$generator];

while ([] !== $data) {
/** @psalm-suppress InvalidOperand */
yield [...(new Unpack())()($data)];
$iterator = new ConcatIterableAggregate([
[0 => 0],
$iterable,
]);

array_shift($data);
}
/** @var array<array-key, T> $generator */
$generator = iterator_to_array((new Normalize())()($iterator));

yield [];
yield from new ReductionIterableAggregate(
$generator,
/**
* @param list<T> $stack
*
* @return list<T>
*/
static fn (array $stack): array => array_slice($stack, 1),
$generator
);
};
}
}

0 comments on commit 1c28be3

Please sign in to comment.