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

ArrayHelper   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 34
ccs 7
cts 7
cp 1
rs 10
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A insertAt() 0 14 2
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