ReduceTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 46
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0
wmc 6
lcom 0
cbo 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B reduce() 0 24 6
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