Intersperse   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 15
c 4
b 0
f 0
dl 0
loc 41
ccs 15
cts 15
cp 1
rs 10
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 36 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace loophp\collection\Operation;
6
7
use ArrayIterator;
8
use Closure;
9
use Generator;
10
use InfiniteIterator;
11
use loophp\iterators\ConcatIterableAggregate;
12
13
/**
14
 * @immutable
15
 *
16
 * @template TKey
17
 * @template T
18
 */
19
final class Intersperse extends AbstractOperation
20
{
21
    /**
22
     * @return Closure(T): Closure(int): Closure(int): Closure(iterable<TKey, T>): Generator<int|TKey, T>
23
     */
24 20
    public function __invoke(): Closure
25
    {
26 20
        return
27
            /**
28
             * @param T $element
29
             *
30
             * @return Closure(int): Closure(int): Closure(iterable<TKey, T>): Generator<int|TKey, T>
31
             */
32 20
            static fn (mixed $element): Closure =>
33
                /**
34
                 * @return Closure(int): Closure(iterable<TKey, T>): Generator<int|TKey, T>
35
                 */
36 20
                static fn (int $atEvery): Closure =>
37
                    /**
38
                     * @return Closure(iterable<TKey, T>): Generator<int|TKey, T>
39
                     */
40 20
                    static fn (int $startAt): Closure =>
41
                        /**
42
                         * @param iterable<TKey, T> $iterable
43
                         *
44
                         * @return Generator<int|TKey, T>
45
                         */
46 20
                        static function (iterable $iterable) use ($element, $atEvery, $startAt): Generator {
47 20
                            $intersperse = (new ConcatIterableAggregate([
48 20
                                new ArrayIterator(array_fill(0, $startAt, 1)),
49 20
                                new InfiniteIterator(new ArrayIterator(range(0, $atEvery - 1))),
50 20
                            ]))->getIterator();
51
52 20
                            foreach ($iterable as $key => $value) {
53 18
                                if (0 === $intersperse->current()) {
54 18
                                    yield $element;
55
                                }
56
57 18
                                yield $key => $value;
58
59 18
                                $intersperse->next();
60
                            }
61 20
                        };
62
    }
63
}
64