Passed
Push โ€” master ( 097598...df8d30 )
by Yo
01:45
created

ArrayHelper::insertAt()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 14
ccs 7
cts 7
cp 1
crap 2
rs 10
1
<?php
2
3
namespace Yoanm\CommonDSA\Helper;
4
5
use ArrayAccess;
6
use Countable;
7
8
class ArrayHelper
9
{
10
    /**
11
     * Insert the value at the given index and push back values from $index to tail index
12
     *
13
     *
14
     * ### Time/Space complexity
15
     * With:
16
     * - ๐‘› equals the provided list length.
17
     * - ๐‘ฅ equals to the number of values to push back (๐‘ฅ = โŸฎ๐‘› โˆ’ ๐Ÿท โˆ’ $indexโŸฏ).
18
     *
19
     * TC: ๐‘‚โŸฎ๐‘ฅโŸฏ - Algo will iterate over each and every value to push back
20
     *
21
     * SC: ๐‘‚โŸฎ๐ŸทโŸฏ - Constant extra space
22
     *
23
     * @param array<mixed> $list โš  Must be a 0 indexed list, 0 to n consecutive indexes !
24
     * @phpstan-param list<mixed> $list
25
     * @param int $index โš  Expected to be between 0 and ๐‘› !
26
     * @param mixed $value
27
     */
28 5
    public static function insertAt(array &$list, int $index, mixed $value): void
29
    {
30 5
        $tailIdx = count($list) - 1;
31
32
        // 1. Move values until the end of original list
33 5
        $prevValue = $value;
34 5
        while ($index <= $tailIdx) {
35
            // Backup original value at $index + replace original value by the previous value
36 3
            [$prevValue, $list[$index]] = [$list[$index], $prevValue]; // @phpstan-ignore parameterByRef.type
37 3
            ++$index;
38
        }
39
40
        // 2. Append the original tail value at the end of the list (=new index !)
41 5
        $list[$index] = $prevValue; // @phpstan-ignore parameterByRef.type
42
    }
43
}
44