Skip to content

Commit e75e437

Browse files
author
Jarek Jakubowski
committed
Add add() method
1 parent e931e3d commit e75e437

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

src/JarJak/Collection/Collection.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,15 @@ public function filter(?\Closure $callback = null)
7070
return static::from(array_filter($this->toArray(), $callback, ARRAY_FILTER_USE_BOTH));
7171
}
7272

73+
public function add($item): self
74+
{
75+
$newIndex = $this->count();
76+
77+
return static::from($this->toArray() + [
78+
$newIndex => $item,
79+
]);
80+
}
81+
7382
public function remove($element)
7483
{
7584
$array = $this->toArray();

tests/CollectionTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,15 @@ public function testFirst(): void
106106
$this->assertSame($collection->first(), 1);
107107
$this->assertSame(55, $sum);
108108
}
109+
110+
public function testAdd(): void
111+
{
112+
$collection = Collection::from(range(1, 3));
113+
$collection = $collection->add(5);
114+
$collection = $collection->add(5);
115+
$collection = $collection->add(3);
116+
117+
$this->assertSame($collection->count(), 6);
118+
$this->assertSame($collection->toArray(), [1, 2, 3, 5, 5, 3]);
119+
}
109120
}

0 commit comments

Comments
 (0)