Skip to content

Commit

Permalink
Implemented Collection::chunk()
Browse files Browse the repository at this point in the history
This method returns smaller arrays of the given size
  • Loading branch information
lorenzo committed Dec 27, 2015
1 parent 0368487 commit 68b30d0
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Collection/CollectionInterface.php
Expand Up @@ -903,6 +903,22 @@ public function zip($items);
*/
public function zipWith($items, $callable);

/**
* Breaks the collection into smaller arrays of the given size.
*
* ### Example:
*
* ```
* $items [1, 2, 3, 4, 5, ,6 ,7 ,8 ,9, 10, 11];
* $chunked = (new Collection($items))->chunk(3)->toList();
* // Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
* ```
*
* @param int $chunkSize The maximum size for each chunk
* @return \Cake\Collection\CollectionInterface
*/
public function chunk($chunkSize);

/**
* Returns whether or not there are elements in this collection
*
Expand Down
20 changes: 20 additions & 0 deletions src/Collection/CollectionTrait.php
Expand Up @@ -601,6 +601,26 @@ public function zipWith($items, $callable)
return new ZipIterator(array_merge([$this], $items), $callable);
}

/**
* {@inheritDoc}
*
*/
public function chunk($chunkSize)
{
return $this->unfold(function ($v, $k, $iterator) use ($chunkSize) {
$values = [$v];
for ($i = 1; $i < $chunkSize; $i++) {
$iterator->next();
if (!$iterator->valid()) {
break;
}
$values[] = $iterator->current();
}

return empty($values) ? $values : [$values];
});
}

/**
* {@inheritDoc}
*
Expand Down
26 changes: 26 additions & 0 deletions tests/TestCase/Collection/CollectionTest.php
Expand Up @@ -1527,4 +1527,30 @@ public function testSerializeWithZipIterator()
$unserialized = unserialize($selialized);
$this->assertEquals($collection->toList(), $unserialized->toList());
}

/**
* Tests the chunk method with exact chunks
*
* @return void
*/
public function testChunk()
{
$collection = new Collection(range(1, 10));
$chunked = $collection->chunk(2)->toList();
$expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]];
$this->assertEquals($expected, $chunked);
}

/**
* Tests the chunk method with overflowing chunk size
*
* @return void
*/
public function testChunkOverflow()
{
$collection = new Collection(range(1, 11));
$chunked = $collection->chunk(2)->toList();
$expected = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11]];
$this->assertEquals($expected, $chunked);
}
}

0 comments on commit 68b30d0

Please sign in to comment.