Skip to content

Commit

Permalink
Implemented Collection::reduce
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Dec 25, 2013
1 parent e6c2e30 commit 7b7118e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Cake/Test/TestCase/Utility/CollectionTest.php
Expand Up @@ -217,4 +217,28 @@ public function testMap() {
$this->assertInstanceOf('\Cake\Utility\Iterator\ReplaceIterator', $map); $this->assertInstanceOf('\Cake\Utility\Iterator\ReplaceIterator', $map);
$this->assertEquals(['a' => 1, 'b' => 4, 'c' => 9], iterator_to_array($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));
}
} }
18 changes: 18 additions & 0 deletions Cake/Utility/Collection.php
Expand Up @@ -223,6 +223,24 @@ public function map(callable $c) {
return new ReplaceIterator($this, $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) { public function mapReduce(callable $map, callable $reduce) {
} }


Expand Down

0 comments on commit 7b7118e

Please sign in to comment.