Skip to content

Commit

Permalink
[8.x] Create Collection chunkInto method (#35295)
Browse files Browse the repository at this point in the history
* create Collection `chunkInto` method

this methods defines the number of chunks we would like to end up with. it fills all non-last chunks first, before placing the remainder in the final chunk.

* rename to `splitIn`

* rename to `splitIn`

forgot the LazyCollection.
  • Loading branch information
browner12 committed Nov 23, 2020
1 parent 056a033 commit ff79432
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
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));
}

/**
* 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

0 comments on commit ff79432

Please sign in to comment.