Skip to content

Commit

Permalink
Added toFilled to Arr class
Browse files Browse the repository at this point in the history
  • Loading branch information
newQuery committed Aug 28, 2024
1 parent b9cf7d3 commit 65add71
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -951,4 +951,35 @@ public static function wrap($value)

return is_array($value) ? $value : [$value];
}

public static function toFilled(array $arr, $value, int $start = 0, int $end = null): array
{
$arrLength = count($arr);

// Adjust the start position for negative values
if ($start < 0) {
$start = max(0, $arrLength + $start);
} else {
$start = min($start, $arrLength);
}

// If end is not provided, set it to the length of the array
if (is_null($end)) {
$end = $arrLength;
} elseif ($end < 0) {
$end = max(0, $arrLength + $end);
} else {
$end = min($end, $arrLength);
}

// Create a copy of the array to avoid modifying the original
$result = $arr;

// Fill the array with the provided value from start to end positions
for ($i = $start; $i < $end; $i++) {
$result[$i] = $value;
}

return $result;
}
}
54 changes: 54 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1502,4 +1502,58 @@ public function testSelect()
],
], Arr::select($array, 'name'));
}

public function testToFilledWithDefaultStartAndEnd()
{
$array = [1, 2, 3, 4, 5];
$result = Arr::toFilled($array, '*');

$this->assertEquals(['*', '*', '*', '*', '*'], $result);
$this->assertEquals([1, 2, 3, 4, 5], $array);
}

public function testToFilledWithStartIndex()
{
$array = [1, 2, 3, 4, 5];
$result = Arr::toFilled($array, '*', 2);

$this->assertEquals([1, 2, '*', '*', '*'], $result);
$this->assertEquals([1, 2, 3, 4, 5], $array);
}

public function testToFilledWithStartAndEndIndices()
{
$array = [1, 2, 3, 4, 5];
$result = Arr::toFilled($array, '*', 1, 4);

$this->assertEquals([1, '*', '*', '*', 5], $result);
$this->assertEquals([1, 2, 3, 4, 5], $array);
}

public function testToFilledWithNegativeIndices()
{
$array = [1, 2, 3, 4, 5];
$result = Arr::toFilled($array, '*', -4, -1);

$this->assertEquals([1, '*', '*', '*', 5], $result);
$this->assertEquals([1, 2, 3, 4, 5], $array);
}

public function testToFilledWithStartGreaterThanEnd()
{
$array = [1, 2, 3, 4, 5];
$result = Arr::toFilled($array, '*', 3, 2);

$this->assertEquals([1, 2, 3, 4, 5], $result); // No change, start is greater than end
$this->assertEquals([1, 2, 3, 4, 5], $array);
}

public function testToFilledWithEmptyArray()
{
$array = [];
$result = Arr::toFilled($array, '*');

$this->assertEquals([], $result); // No change, array is empty
$this->assertEquals([], $array);
}
}

0 comments on commit 65add71

Please sign in to comment.