phpstreams\Stream::reduce PHP Method

reduce() public method

The given is applied to every item in the stream in no particular order. The result is then returned. In order for the callable to be a proper reductor, it should be:
  • Commutative, so op($a, $b) is equal to op($b, $a), and
  • Should preserve respect the given identity, i.e. op($a, $identity) = $identity.
If any of these properties do not hold, the output of this function is not defined.
public reduce ( mixed $identity, callable $binaryOp ) : mixed
$identity mixed The identity element.
$binaryOp callable A reduction function, respecting the properties above.
return mixed
    public function reduce($identity, callable $binaryOp)
    {
        $cur = $identity;
        foreach ($this as $value) {
            $cur = $binaryOp($cur, $value);
        }
        return $cur;
    }

Usage Example

Example #1
0
 public function testReduce()
 {
     $instance = new Stream([1, 2, 3, 4]);
     $result = $instance->reduce(0, function ($a, $b) {
         return $a + $b;
     });
     $this->assertEquals(10, $result);
 }