Browse Source

Making Collection::sumOf() use an identity by default

Jose Lorenzo Rodriguez 10 years ago
parent
commit
a340d8b00a

+ 5 - 1
src/Collection/CollectionInterface.php

@@ -444,13 +444,17 @@ interface CollectionInterface extends Iterator, JsonSerializable
      * $total = (new Collection($items))->sumOf('invoice.total');
      *
      * // Total: 300
+     *
+     * $total = (new Colletion([1, 2, 3]))->sumOf();
+     * // Total: 6
      * ```
      *
      * @param string|callable $matcher The property name to sum or a function
+     * If no value is passed, an identity function will be used.
      * that will return the value of the property to sum.
      * @return float|int
      */
-    public function sumOf($matcher);
+    public function sumOf($matcher = null);
 
     /**
      * Returns a new collection with the elements placed in a random order,

+ 5 - 1
src/Collection/CollectionTrait.php

@@ -242,8 +242,12 @@ trait CollectionTrait
      * {@inheritDoc}
      *
      */
-    public function sumOf($matcher)
+    public function sumOf($matcher = null)
     {
+        if ($matcher === null) {
+            return array_sum($this->toList());
+        }
+
         $callback = $this->_propertyExtractor($matcher);
         $sum = 0;
         foreach ($this as $k => $v) {

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

@@ -1367,4 +1367,18 @@ class CollectionTest extends TestCase
         $collection = new Collection([]);
         $this->assertNull($collection->last());
     }
+
+    /**
+     * Tests sumOf with no parameters
+     *
+     * @return void
+     */
+    public function testSumOfWithIdentity()
+    {
+        $collection = new Collection([1, 2, 3]);
+        $this->assertEquals(6, $collection->sumOf());
+
+        $collection = new Collection(['a' => 1, 'b' => 4, 'c' => 6]);
+        $this->assertEquals(11, $collection->sumOf());
+    }
 }