Completed
Push — master ( 38f87f...231e76 )
by Karsten
02:16
created

MedianOperation   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B apply() 0 25 4
1
<?php
2
/**
3
 * File was created 07.05.2015 09:11
4
 *
5
 * @author Karsten J. Gerber <[email protected]>
6
 */
7
8
namespace PeekAndPoke\Component\Psi\Operation\Terminal;
9
10
use PeekAndPoke\Component\Psi\Interfaces\Operation\TerminalOperationInterface;
11
12
/**
13
 * MedianOperation
14
 *
15
 * @author Karsten J. Gerber <[email protected]>
16
 */
17
class MedianOperation implements TerminalOperationInterface
18
{
19
    /**
20
     * {@inheritdoc}
21
     *
22
     * @return float
23
     */
24 11
    public function apply(\Iterator $set)
25
    {
26
        /** @var float[] $data */
27 11
        $data  = array_values(iterator_to_array($set));
28 11
        $count = count($data);
29
30 11
        if ($count === 0) {
31 1
            return 0;
32
        }
33
34 10
        sort($data);
35
36 10
        $middle = (($count + 1) / 2) - 1;
37 10
        $left   = (int) floor($middle);
38 10
        $right  = (int) ceil($middle);
39
40 10
        $leftVal = $data[$left];
41 10
        $rightVal = $data[$right];
42
43 10
        if (!is_scalar($leftVal) || !is_scalar($rightVal)) {
44 2
            return 0;
45
        }
46
47 8
        return ($data[$left] + $data[$right]) / 2;
48
    }
49
}
50