Skip to content
Permalink
Browse files

Implemented Collection::sumOf()

  • Loading branch information...
lorenzo committed Sep 17, 2014
1 parent 7e3ccbe commit e94fbfeb8ace6363044022a810809de027527b73
Showing with 49 additions and 0 deletions.
  1. +31 −0 src/Collection/CollectionTrait.php
  2. +18 −0 tests/TestCase/Collection/CollectionTest.php
@@ -515,6 +515,37 @@ public function countBy($callback) {
return new Collection(new MapReduce($this, $mapper, $reducer));
}
/**
* Returns the total sum of all the values extracted with $matcher
* or of this collection.
*
* ###Example:
*
* {{{
* $items = [
* ['invoice' => ['total' => 100],
* ['invoice' => ['total' => 200]
* ];
*
* $total = (new Collection($items))->sumOf('invoice.total');
*
* // Total: 300
* }}}
*
* @param string|callable $matcher The property name to sum or a function
* that will return the value of the property to sum.
* @return float|int
*/
public function sumOf($matcher) {
$callback = $this->_propertyExtractor($matcher);
$sum = 0;
foreach ($this as $k => $v) {
$sum += $callback($v, $k);
}
return $sum;
}
/**
* Returns a new collection with the elements placed in a random order,
* this function does not preserve the original keys in the collection.
@@ -934,4 +934,22 @@ public function testListNestedWithCallable() {
$this->assertEquals(range(1, 5), $collection->extract('id')->toArray(false));
}
/**
* Tests the sumOf method
*
* @return void
*/
public function testSumOf() {
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$this->assertEquals(300, (new Collection($items))->sumOf('invoice.total'));
$sum = (new Collection($items))->sumOf(function($v) {
return $v['invoice']['total'] * 2;
});
$this->assertEquals(600, $sum);
}
}

0 comments on commit e94fbfe

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