Skip to content
Permalink
Browse files

Implemeting the zipWith() method

  • Loading branch information...
lorenzo committed May 16, 2015
1 parent d311596 commit c8c60fb36b3518fa1c03e04b7781c37ab03ecd20
@@ -538,9 +538,12 @@ public function zip($items)
public function zipWith($items, $callable)
{
$args = func_get_args();
$callable = array_pop($args);
return new ZipIterator($args, $callable);
$items = [$items];
if (func_num_args() > 2) {
$items = func_get_args();
$callable = array_pop($items);
}
return new ZipIterator(array_merge([$this], $items), $callable);
}
/**
@@ -34,8 +34,6 @@ class ZipIterator extends MultipleIterator implements CollectionInterface
use CollectionTrait;
protected $_firstIterator;
protected $_callback;
public function __construct(array $sets, $callable = null)
@@ -47,9 +45,17 @@ public function __construct(array $sets, $callable = null)
$this->_callback = $callable;
parent::__construct(MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_NUMERIC);
$this->_firstIterator = current($sets);
foreach ($sets as $set) {
$this->attachIterator($set);
}
}
public function current()
{
if ($this->_callback === null) {
return parent::current();
}
return call_user_func_array($this->_callback, parent::current());
}
}
@@ -1308,4 +1308,23 @@ public function testZip()
[2, 4, 6, 8, 10]
], $zipped->toList());
}
/**
* Tests the zipWith() method
*
* @return void
*/
public function testZipWith()
{
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], function ($a, $b) {
return $a * $b;
});
$this->assertEquals([3, 8], $zipped->toList());
$zipped = $collection->zipWith([3, 4], [5, 6, 7], function () {
return array_sum(func_get_args());
});
$this->assertEquals([9, 12], $zipped->toList());
}
}

0 comments on commit c8c60fb

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