laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.62k stars 11.03k forks source link

Introducing Arr::chunkBy(). Split an iterable into chunks based on a callback function. #53603

Closed mdariftiens closed 16 hours ago

mdariftiens commented 1 day ago

Introducing Arr::chunkBy(). Split an iterable into chunks based on a callback function. Each chunk will contain consecutive elements until the callback's return value changes

Detailed Impact:

ChunkBy Method: Benefit: Dynamically segments iterable based on conditions. Common Use: Log analysis, temporal grouping, or state-based processing. Performance: Efficient for moderately sized iterable with clear grouping logic.

Example usages:


    $orders = [
            ['id' => 1, 'user_id' => 1],
            ['id' => 2, 'user_id' => 1],
            ['id' => 3, 'user_id' => 2],
        ];

    $grouped = Arr::chunkBy($orders, fn ($order) => $order['user_id']);

        $this->assertSame(
            $grouped,
            [
                [
                    0 => [
                        'id' => 1,
                        'user_id' => 1,
                    ],
                    1 => [
                        'id' => 2,
                        'user_id' => 1,
                    ],
                ],
                [
                    2 => [
                        'id' => 3,
                        'user_id' => 2,
                    ],
                ],
            ]
        );
github-actions[bot] commented 1 day ago

Thanks for submitting a PR!

Note that draft PR's are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface.

Pull requests that are abandoned in draft may be closed due to inactivity.

MatusBoa commented 1 day ago

Would be great if this supports iterable so generators with large dataset could be chunked as well.

mdariftiens commented 1 day ago

@MatusBoa thanks for your comment. Updated code and test for the supports iterable.

taylorotwell commented 16 hours ago

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions!

taylorotwell commented 16 hours ago

For these types of methods, it's best to have practical use cases in real world applications provided.