Add remove method

This commit is contained in:
Daniel Winning 2025-04-09 02:45:41 +01:00
parent a9665c3611
commit 7cc6e66313
3 changed files with 54 additions and 3 deletions

View file

@ -14,9 +14,24 @@ class AbstractCollection implements CollectionInterface
public function add(mixed $item): void
{
if (null === $item) {
return;
}
$this->items[] = $item;
}
public function remove(mixed $item): void
{
$key = array_search($item, $this->items, true);
if ($key) {
unset($this->items[$key]);
}
$this->items = array_values($this->items);
}
public function toArray(): array
{
return $this->items;

View file

@ -1,4 +1,5 @@
<?php
declare(strict_types=1);
namespace Loom\Utility\Collection\Interface;
@ -6,5 +7,6 @@ namespace Loom\Utility\Collection\Interface;
interface CollectionInterface
{
public function add(mixed $item): void;
public function remove(mixed $item): void;
public function toArray(): array;
}

View file

@ -19,20 +19,54 @@ class CollectionTest extends TestCase
$this->assertEquals($expectedResult, $collection->toArray());
}
#[DataProvider('removeDataProvider')]
public function testRemove(array $startingArray, mixed $itemToRemove, array $expectedResult): void
{
$collection = new Collection($startingArray);
$collection->remove($itemToRemove);
$this->assertEquals($expectedResult, $collection->toArray());
}
public static function addDataProvider(): array
{
return [
[
'startingItems' => ['apple', 'banana', 'cherry'],
'itemToAdd' => 'grape',
'expectedResult' => ['apple', 'banana', 'cherry', 'grape'],
'startingItems' => ['A', 'B', 'C'],
'itemToAdd' => 'D',
'expectedResult' => ['A', 'B', 'C', 'D'],
],
[
'startingItems' => [],
'itemToAdd' => 1,
'expectedResult' => [1],
],
[
'startingItems' => [],
'itemToAdd' => null,
'expectedResult' => [],
],
];
}
public static function removeDataProvider(): array
{
return [
[
'startingArray' => ['A', 'B', 'C'],
'itemToRemove' => 'B',
'expectedResult' => ['A', 'C'],
],
[
'startingArray' => ['A', 'B', 'C'],
'itemToRemove' => 'orange',
'expectedResult' => ['A', 'B', 'C'],
],
[
'startingArray' => [],
'itemToRemove' => 'A',
'expectedResult' => [],
],
];
}
}