Skip to content
Permalink
Browse files

Implemented Collection::reduce

  • Loading branch information...
lorenzo committed Dec 25, 2013
1 parent e6c2e30 commit 7b7118ee34341bf66855d4991c995dc0790007b2
Showing with 42 additions and 0 deletions.
  1. +24 −0 Cake/Test/TestCase/Utility/CollectionTest.php
  2. +18 −0 Cake/Utility/Collection.php
@@ -217,4 +217,28 @@ public function testMap() {
$this->assertInstanceOf('\Cake\Utility\Iterator\ReplaceIterator', $map);
$this->assertEquals(['a' => 1, 'b' => 4, 'c' => 9], iterator_to_array($map));
}
/**
* Tests reduce
*
* @return void
*/
public function testReduce() {
$items = ['a' => 1, 'b' => 2, 'c' => 3];
$collection = new Collection($items);
$callable = $this->getMock('stdClass', ['__invoke']);
$callable->expects($this->at(0))
->method('__invoke')
->with(10, 1, 'a')
->will($this->returnValue(11));
$callable->expects($this->at(1))
->method('__invoke')
->with(11, 2, 'b')
->will($this->returnValue(13));
$callable->expects($this->at(2))
->method('__invoke')
->with(13, 3, 'c')
->will($this->returnValue(16));
$this->assertEquals(16, $collection->reduce($callable, 10));
}
}
@@ -223,6 +223,24 @@ public function map(callable $c) {
return new ReplaceIterator($this, $c);
}
/**
* Folds the values in this collection to a single value, as the result of
* applying the callback function to all elements. $zero is the initial state
* of the reduction, and each successive step should of it should be returned
* by the callback function.
*
* The callback function is
*
* @return void
*/
public function reduce(callable $c, $zero) {
$result = $zero;
foreach ($this as $k => $value) {
$result = $c($result, $value, $k);
}
return $result;
}
public function mapReduce(callable $map, callable $reduce) {
}

0 comments on commit 7b7118e

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