ReduceTrait::reduce()   B
last analyzed

Complexity

Conditions 6
Paths 13

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
nc 13
nop 2
dl 0
loc 24
ccs 14
cts 14
cp 1
crap 6
rs 8.9137
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Zicht Online <http://zicht.nl>
4
 */
5
6
namespace Zicht\Itertools\lib\Traits;
7
8
use Zicht\Itertools;
9
10
trait ReduceTrait
11
{
12
    /**
13
     * Reduce an iterator to a single value
14
     *
15
     * > iter\iterable([1,2,3])->reduce()
16
     * 6
17
     *
18
     * > iter\iterable([1,2,3])->reduce('max')
19
     * 3
20
     *
21
     * > iter\iterable([1,2,3])->reduce('sub', 10)
22
     * 4
23
     *
24
     * > iter\iterable([])->reduce('min', 1)
25
     * 1
26
     *
27
     * @param string|\Closure $closure
28
     * @param mixed $initializer
29
     * @return mixed
30
     */
31 58
    public function reduce($closure = 'add', $initializer = null)
32
    {
33 58
        if ($this instanceof \Iterator) {
34 57
            $closure = $closure instanceof \Closure ? $closure : Itertools\reductions\get_reduction($closure);
0 ignored issues
show
Deprecated Code introduced by
The function Zicht\Itertools\reductions\get_reduction() has been deprecated with message: please use the reduction functions directly, will be removed in version 3.0

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
35 54
            $this->rewind();
36
37 54
            if (null === $initializer) {
38 46
                if ($this->valid()) {
39 45
                    $initializer = $this->current();
40 45
                    $this->next();
41
                }
42
            }
43
44 54
            $accumulatedValue = $initializer;
45 54
            while ($this->valid()) {
46 50
                $accumulatedValue = $closure($accumulatedValue, $this->current());
47 49
                $this->next();
48
            }
49
50 53
            return $accumulatedValue;
51
        }
52
53 1
        return null;
54
    }
55
}
56