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

[5.3] Add split method to collection class #15302

Merged
merged 6 commits into from
Sep 6, 2016
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -920,6 +920,23 @@ public function slice($offset, $length = null)
return new static(array_slice($this->items, $offset, $length, true));
}

/**
* Split a collection into a certain number of groups.
*
* @param int $numberOfGroups
* @return static
*/
public function split($numberOfGroups)
{
if ($this->isEmpty()) {
return new static;
}

$groupSize = ceil($this->count() / $numberOfGroups);

return $this->chunk($groupSize);
}

/**
* Chunk the underlying collection array.
*
Expand Down
48 changes: 48 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1554,6 +1554,54 @@ public function testCollectonFromTraversableWithKeys()
$collection = new Collection(new \ArrayObject(['foo' => 1, 'bar' => 2, 'baz' => 3]));
$this->assertEquals(['foo' => 1, 'bar' => 2, 'baz' => 3], $collection->toArray());
}

public function testSplitCollectionWithADivisableCount()
{
$collection = new Collection(['a', 'b', 'c', 'd']);

$this->assertEquals(
[['a', 'b'], ['c', 'd']],
$collection->split(2)->map(function (Collection $chunk) {
return $chunk->values()->toArray();
})->toArray()
);
}

public function testSplitCollectionWithAnUndivisableCount()
{
$collection = new Collection(['a', 'b', 'c']);

$this->assertEquals(
[['a', 'b'], ['c']],
$collection->split(2)->map(function (Collection $chunk) {
return $chunk->values()->toArray();
})->toArray()
);
}

public function testSplitCollectionWithCountLessThenDivisor()
{
$collection = new Collection(['a']);

$this->assertEquals(
[['a']],
$collection->split(2)->map(function (Collection $chunk) {
return $chunk->values()->toArray();
})->toArray()
);
}

public function testSplitEmptyCollection()
{
$collection = new Collection();

$this->assertEquals(
[],
$collection->split(2)->map(function (Collection $chunk) {
return $chunk->values()->toArray();
})->toArray()
);
}
}

class TestAccessorEloquentTestStub
Expand Down