Completed
Push — master ( 01762c...256c3c )
by Karsten
02:12
created

MedianOperation   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 4
lcom 0
cbo 0
dl 0
loc 29
ccs 12
cts 12
cp 1
rs 10
c 1
b 0
f 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A apply() 0 21 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 float[] $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