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

[8.x] Create Collection chunkInto method #35295

Merged
merged 3 commits into from Nov 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/Illuminate/Collections/Collection.php
Expand Up @@ -1041,6 +1041,17 @@ public function split($numberOfGroups)
return $groups;
}

/**
* Split a collection into a certain number of groups, and fill the first groups completely.
*
* @param int $numberOfGroups
* @return static
*/
public function splitIn($numberOfGroups)
{
return $this->chunk(ceil($this->count() / $numberOfGroups));
}

/**
* Chunk the collection into chunks of the given size.
*
Expand Down
11 changes: 11 additions & 0 deletions src/Illuminate/Collections/LazyCollection.php
Expand Up @@ -1057,6 +1057,17 @@ public function chunk($size)
});
}

/**
* Split a collection into a certain number of groups, and fill the first groups completely.
*
* @param int $numberOfGroups
* @return static
*/
public function splitIn($numberOfGroups)
{
return $this->chunk(ceil($this->count() / $numberOfGroups));
Copy link
Member

Choose a reason for hiding this comment

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

This enumerates the whole collection twice 😢

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'll admit I don't understand the lazy collections as well, so if there's a better way to do this, definitely open to it.

}

/**
* Chunk the collection into chunks with a callback.
*
Expand Down
16 changes: 16 additions & 0 deletions tests/Support/SupportCollectionTest.php
Expand Up @@ -1645,6 +1645,22 @@ public function testChunkWhenGivenLessThanZero($collection)
);
}

/**
* @dataProvider collectionClassProvider
*/
public function testSplitIn($collection)
{
$data = new $collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
$data = $data->splitIn(3);

$this->assertInstanceOf($collection, $data);
$this->assertInstanceOf($collection, $data->first());
$this->assertCount(3, $data);
$this->assertEquals([1, 2, 3, 4], $data->get(0)->values()->toArray());
$this->assertEquals([5, 6, 7, 8], $data->get(1)->values()->toArray());
$this->assertEquals([9, 10], $data->get(2)->values()->toArray());
}

/**
* @dataProvider collectionClassProvider
*/
Expand Down