Skip to content

Commit

Permalink
Adding more tests and the code
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed May 16, 2015
1 parent ac97df1 commit d311596
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
55 changes: 55 additions & 0 deletions src/Collection/Iterator/ZipIterator.php
@@ -0,0 +1,55 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Collection\Iterator;

use Cake\Collection\Collection;
use Cake\Collection\CollectionInterface;
use Cake\Collection\CollectionTrait;
use MultipleIterator;

/**
* Creates an iterator that returns elements grouped in pairs
*
* ### Example
*
* {{{
* $iterator = new ZipIterator([1, 2], [3, 4]);
* $iterator->toList(); // Returns [[1, 2], [3, 4]]
* }}}
*/
class ZipIterator extends MultipleIterator implements CollectionInterface
{

use CollectionTrait;

protected $_firstIterator;

protected $_callback;

public function __construct(array $sets, $callable = null)
{
$sets = array_map(function ($items) {
return (new Collection($items))->unwrap();
}, $sets);

$this->_callback = $callable;
parent::__construct(MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_NUMERIC);

$this->_firstIterator = current($sets);
foreach ($sets as $set) {
$this->attachIterator($set);
}
}
}
9 changes: 8 additions & 1 deletion tests/TestCase/Collection/CollectionTest.php
Expand Up @@ -1299,6 +1299,13 @@ public function testZip()

$collection = new Collection([1, 2]);
$zipped = $collection->zip([3]);
$this->assertEquals([[1, 3], [2, null]], $zipped->toList());
$this->assertEquals([[1, 3]], $zipped->toList());

$collection = new Collection([1, 2]);
$zipped = $collection->zip([3, 4], [5, 6], [7, 8], [9, 10, 11]);
$this->assertEquals([
[1, 3, 5, 7, 9],
[2, 4, 6, 8, 10]
], $zipped->toList());
}
}

0 comments on commit d311596

Please sign in to comment.