Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Conversation

liamduckett
Copy link
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
{
if ($size <= 0) {
return static::empty();
}

return new static(function () use ($size) {
$add = match ($preserveKeys) {
Copy link
Contributor Author

@liamduckett liamduckett Mar 5, 2025

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).

@taylorotwell taylorotwell merged commit 77672fd into laravel:12.x Mar 6, 2025
41 checks passed
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