Passed
Push — master ( 904df5...62fce2 )
by Pol
02:08
created

Entropy   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 14
c 1
b 0
f 1
dl 0
loc 47
ccs 22
cts 22
cp 1
rs 10
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 42 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace loophp\collection\Operation;
6
7
use Closure;
8
use Generator;
9
use loophp\collection\Collection;
10
use loophp\collection\Contract\Collection as CollectionInterface;
11
12
/**
13
 * @immutable
14
 *
15
 * @template TKey
16
 * @template T
17
 */
18
final class Entropy extends AbstractOperation
19
{
20
    /**
21
     * @return Closure(iterable<TKey, T>): Generator<int, int<0,1>|float>
22
     */
23 3
    public function __invoke(): Closure
24
    {
25
        /** @var Closure(iterable<TKey, T>): Generator<int, int<0,1>|float> $pipe */
26 3
        $pipe = (new Pipe())()(
27 3
            (
28
                /**
29
                 * @param iterable<TKey, T> $iterable
30
                 *
31
                 * @return CollectionInterface<int, T>
32
                 */
33 3
                static fn (iterable $iterable): CollectionInterface => Collection::fromIterable($iterable)->normalize()->squash()
34 3
            ),
35 3
            (new Map())()(
36
                /**
37
                 * @param T $_
38
                 * @param int $key
39
                 * @param Collection<TKey, T> $collection
40
                 */
41 3
                static fn (mixed $_, int $key, Collection $collection): float => $collection
42 3
                    ->limit($key + 1)
43 3
                    ->frequency()
44 3
                    ->map(
45
                        /**
46
                         * @param T $_
47
                         */
48 3
                        static fn (mixed $_, int $freq): float => $freq / ($key + 1)
49 3
                    )
50 3
                    ->reduce(
51 3
                        static fn (float $acc, float $p, int $_, Collection $c): float => 0 === $key ? $acc : $acc - $p * log($p, 2) / log($c->count(), 2),
52 3
                        0
53 3
                    )
54 3
            ),
55 3
            (new Map())()(
56
                /**
57
                 * @return int<0,1>|float
58
                 */
59 3
                static fn (float $value): float|int => (0.0 === $value || 1.0 === $value) ? (int) $value : $value
0 ignored issues
show
introduced by
The condition 1.0 === $value is always false.
Loading history...
60 3
            )
61 3
        );
62
63
        // Point free style
64 3
        return $pipe;
65
    }
66
}
67