Skip to content

Commit

Permalink
[5.3] Add split method to collection class (#15302)
Browse files Browse the repository at this point in the history
* add split function to collection

* fix nitpicks

* fix cs

* more cs fixes

* moar cs

* return new instance
  • Loading branch information
freekmurze authored and taylorotwell committed Sep 6, 2016
1 parent 0bea680 commit 2bfef8b
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
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

0 comments on commit 2bfef8b

Please sign in to comment.