Skip to content

[12.x] Feature: Collection chunk without preserving keys#54916

Merged
taylorotwell merged 3 commits into
laravel:12.xfrom
liamduckett:feature/collection-chunk-dont-preserve-keys
Mar 6, 2025
Merged

[12.x] Feature: Collection chunk without preserving keys#54916
taylorotwell merged 3 commits into
laravel:12.xfrom
liamduckett:feature/collection-chunk-dont-preserve-keys

Conversation

@liamduckett

Copy link
Copy Markdown
Contributor

Hey, this PR allows using the existing Collection::chunk and LazyCollection::chunk methods, without preserving keys.

I haven't added the new parameter to the Enumerable interface (despite the chunk method being declared in it) for backwards compatibility. Although Collection and LazyCollection are the frameworks only implementations of Enumerable, end user code may have additional implementations.

The new parameter does not break existing adherence to the interface, as it is optional (due to having a default value).

@liamduckett liamduckett changed the title Feature/collection chunk dont preserve keys [12.x] Feature: Collection chunk without preserving keys Mar 5, 2025
}

return new static(function () use ($size) {
$add = match ($preserveKeys) {

@liamduckett liamduckett Mar 5, 2025

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My first pass looked more like:

return new static(function () use ($size, $preserveKeys) {
    $iterator = $this->getIterator();

    while ($iterator->valid()) {
        $chunk = [];

        while (true) {
            if ($preserveKeys === false) {
                $chunk[] = $iterator->current();
            } else {
                $chunk[$iterator->key()] = $iterator->current();
            }

            if (count($chunk) < $size) {
                $iterator->next();

                if (! $iterator->valid()) {
                    break;
                }
            } else {
                break;
            }
        }

        yield new static($chunk);

        $iterator->next();
    }
});

I opted for this (match) approach due to LazyCollections perfomance oriented nature (appreciate this is at the cost of readability).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants