Browse Source

Initial implementation of Collection::zip()

Jose Lorenzo Rodriguez 11 years ago
parent
commit
ac97df1f0a
2 changed files with 29 additions and 0 deletions
  1. 13 0
      src/Collection/CollectionTrait.php
  2. 16 0
      tests/TestCase/Collection/CollectionTest.php

+ 13 - 0
src/Collection/CollectionTrait.php

@@ -28,6 +28,7 @@ use Cake\Collection\Iterator\SortIterator;
 use Cake\Collection\Iterator\StoppableIterator;
 use Cake\Collection\Iterator\TreeIterator;
 use Cake\Collection\Iterator\UnfoldIterator;
+use Cake\Collection\Iterator\ZipIterator;
 use Iterator;
 use LimitIterator;
 use RecursiveIteratorIterator;
@@ -530,6 +531,18 @@ trait CollectionTrait
         return $result instanceof CollectionInterface ? $result: new Collection($result);
     }
 
+    public function zip($items)
+    {
+        return new ZipIterator(array_merge([$this], func_get_args()));
+    }
+
+    public function zipWith($items, $callable)
+    {
+        $args = func_get_args();
+        $callable = array_pop($args);
+        return new ZipIterator($args, $callable);
+    }
+
     /**
      * {@inheritDoc}
      *

+ 16 - 0
tests/TestCase/Collection/CollectionTest.php

@@ -1285,4 +1285,20 @@ class CollectionTest extends TestCase
         $collection = $collection->filter();
         $this->assertTrue($collection->isEmpty());
     }
+
+    /**
+     * Tests the zip() method
+     *
+     * @return void
+     */
+    public function testZip()
+    {
+        $collection = new Collection([1, 2]);
+        $zipped = $collection->zip([3, 4]);
+        $this->assertEquals([[1, 3], [2, 4]], $zipped->toList());
+
+        $collection = new Collection([1, 2]);
+        $zipped = $collection->zip([3]);
+        $this->assertEquals([[1, 3], [2, null]], $zipped->toList());
+    }
 }