Passed
Push — master ( 9e9b54...8c04f5 )
by
unknown
38s
created

ReduceTrait::reduce()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 14
nc 13
nop 2
dl 0
loc 25
ccs 14
cts 14
cp 1
crap 6
rs 8.439
c 2
b 0
f 0
1
<?php
2
/**
3
 * @author Boudewijn Schoon <[email protected]>
4
 * @copyright Zicht Online <http://zicht.nl>
5
 */
6
7
namespace Zicht\Itertools\lib\Traits;
8
9
use Zicht\Itertools;
10
11
trait ReduceTrait
12
{
13
    /**
14
     * Reduce an iterator to a single value
15
     *
16
     * > iter\iterable([1,2,3])->reduce()
17
     * 6
18
     *
19
     * > iter\iterable([1,2,3])->reduce('max')
20
     * 3
21
     *
22
     * > iter\iterable([1,2,3])->reduce('sub', 10)
23
     * 4
24
     *
25
     * > iter\iterable([])->reduce('min', 1)
26
     * 1
27
     *
28
     * @param string|\Closure $closure
29
     * @param mixed $initializer
30
     * @return mixed
31
     */
32 56
    public function reduce($closure = 'add', $initializer = null)
33
    {
34 56
        if ($this instanceof \Iterator) {
35
36 55
            $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...
37 52
            $this->rewind();
38
39 52
            if (null === $initializer) {
40 44
                if ($this->valid()) {
41 43
                    $initializer = $this->current();
42 43
                    $this->next();
43
                }
44
            }
45
46 52
            $accumulatedValue = $initializer;
47 52
            while ($this->valid()) {
48 48
                $accumulatedValue = $closure($accumulatedValue, $this->current());
49 47
                $this->next();
50
            }
51
52 51
            return $accumulatedValue;
53
        }
54
55 1
        return null;
56
    }
57
}
58