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

MedianOperation::apply()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 14
cts 14
cp 1
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 14
nc 3
nop 1
crap 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