Skip to content
Permalink
Browse files

Preserve keys option on Collection::chunk

  • Loading branch information...
jorisvaesen authored and markstory committed Sep 22, 2016
1 parent 3a47ac5 commit a4cbd70aae2bea95e3a373e028569fd62d409258
@@ -915,9 +915,10 @@ public function zipWith($items, $callable);
* ```
*
* @param int $chunkSize The maximum size for each chunk
* @param boolean $preserveKeys If the keys of the array should be preserved
* @return \Cake\Collection\CollectionInterface
*/
public function chunk($chunkSize);
public function chunk($chunkSize, $preserveKeys = false);
/**
* Returns whether or not there are elements in this collection
@@ -627,16 +627,24 @@ public function zipWith($items, $callable)
* {@inheritDoc}
*
*/
public function chunk($chunkSize)
public function chunk($chunkSize, $preserveKeys = false)
{
return $this->map(function ($v, $k, $iterator) use ($chunkSize) {
$values = [$v];
return $this->map(function ($v, $k, $iterator) use ($chunkSize, $preserveKeys) {
$key = 0;
if ($preserveKeys) {
$key = $k;
}
$values = [$key => $v];
for ($i = 1; $i < $chunkSize; $i++) {
$iterator->next();
if (!$iterator->valid()) {
break;
}
$values[] = $iterator->current();
if ($preserveKeys) {
$values[$iterator->key()] = $iterator->current();
} else {
$values[] = $iterator->current();
}
}
return $values;
@@ -1770,6 +1770,19 @@ public function testChunkNested()
$this->assertEquals($expected, $chunked);
}
/**
* Tests the chunk method with preserved keys
*
* @return void
*/
public function testChunkPreserveKeys()
{
$collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
$chunked = $collection->chunk(2, true)->toList();
$expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6], ['g' => 7]];
$this->assertEquals($expected, $chunked);
}
/**
* Tests cartesianProduct
*
@@ -1961,4 +1974,17 @@ public function testTransposeUnEvenLengthShouldThrowException()
$collection->transpose();
}
/**
* Tests the chunk method with preserved keys
*
* @return void
*/
public function testChunkPreserveKeys()
{
$collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
$chunked = $collection->chunk(2, true)->toList();
$expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6], ['g' => 7]];
$this->assertEquals($expected, $chunked);
}
}

0 comments on commit a4cbd70

Please sign in to comment.
You can’t perform that action at this time.