MedianOperation::apply()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 20
c 0
b 0
f 0
ccs 12
cts 12
cp 1
rs 9.9
cc 4
nc 5
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\TerminalOperation;
11
12
/**
13
 * MedianOperation
14
 *
15
 * @author Karsten J. Gerber <[email protected]>
16
 */
17
class MedianOperation implements TerminalOperation
18
{
19
    /**
20
     * {@inheritdoc}
21
     *
22
     * @return float
23
     */
24 15
    public function apply(\Iterator $set)
25
    {
26
        /** @var mixed[] $data */
27 15
        $data  = array_values(iterator_to_array($set));
28 15
        $count = count($data);
29
30 15
        if ($count === 0) {
31 1
            return 0;
32
        }
33
34 14
        sort($data);
35
36 14
        $middle = (($count + 1) / 2) - 1;
37 14
        $left   = (int) floor($middle);
38 14
        $right  = (int) ceil($middle);
39
40 14
        $leftVal  = $data[$left];
41 14
        $rightVal = $data[$right];
42
43 14
        return is_scalar($leftVal) && is_scalar($rightVal) ? ($data[$left] + $data[$right]) / 2 : 0;
44
    }
45
}
46