Intersperse::__invoke()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 36
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3

Importance

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