diff --git a/src/Contract/Operation/Chunkable.php b/src/Contract/Operation/Chunkable.php index 6bcec354..9f2a51eb 100644 --- a/src/Contract/Operation/Chunkable.php +++ b/src/Contract/Operation/Chunkable.php @@ -17,7 +17,7 @@ interface Chunkable * * @see https://loophp-collection.readthedocs.io/en/stable/pages/api.html#chunk * - * @return Collection> + * @return Collection> */ public function chunk(int ...$sizes): Collection; } diff --git a/src/Operation/Chunk.php b/src/Operation/Chunk.php index 853d72fd..aea472ed 100644 --- a/src/Operation/Chunk.php +++ b/src/Operation/Chunk.php @@ -18,47 +18,45 @@ final class Chunk extends AbstractOperation { /** - * @return Closure(int...): Closure(iterable): Generator> + * @return Closure(int...): Closure(iterable): Generator> */ public function __invoke(): Closure { return /** - * @return Closure(iterable): Generator> + * @return Closure(iterable): Generator> */ static fn (int ...$sizes): Closure => /** * @param iterable $iterable * - * @return Generator> + * @return Generator> */ static function (iterable $iterable) use ($sizes): Generator { $sizesCount = count($sizes); - $i = 0; - $values = []; + $chunkIndex = 0; + $chunk = []; foreach ($iterable as $value) { - $size = $sizes[$i % $sizesCount]; + $size = $sizes[$chunkIndex % $sizesCount]; if (0 >= $size) { return; } - if (count($values) !== $size) { - $values[] = $value; + $chunk[] = $value; - continue; - } - - ++$i; + if (count($chunk) >= $size) { + ++$chunkIndex; - yield $values; + yield $chunk; - $values = [$value]; + $chunk = []; + } } - if ([] !== $values) { - yield $values; + if ([] !== $chunk) { + yield $chunk; } }; } diff --git a/tests/static-analysis/chunk.php b/tests/static-analysis/chunk.php index f5ff647f..1316b1b1 100644 --- a/tests/static-analysis/chunk.php +++ b/tests/static-analysis/chunk.php @@ -8,18 +8,18 @@ use loophp\collection\Contract\Collection as CollectionInterface; /** - * @param CollectionInterface> $collection + * @param CollectionInterface> $collection */ function chunk_checkList(CollectionInterface $collection): void {} /** - * @param CollectionInterface> $collection + * @param CollectionInterface> $collection */ function chunk_checkMap(CollectionInterface $collection): void {} chunk_checkList(Collection::fromIterable(range(0, 6))->chunk(1)); chunk_checkList(Collection::fromIterable(range(0, 6))->chunk(1, 2)); -// These should work but Psalm restricts type to list<'baz'|'taz'> +// These should work but Psalm restricts type to non-empty-list<'baz'|'taz'> /** @psalm-suppress InvalidArgument */ chunk_checkMap(Collection::fromIterable(['foo' => 'bar', 'baz' => 'taz'])->chunk(1)); /** @psalm-suppress InvalidArgument */