Skip to content

Commit

Permalink
Add filter method to Collection
Browse files Browse the repository at this point in the history
  • Loading branch information
olivervogel committed Sep 30, 2023
1 parent baf1652 commit 7577986
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,21 @@ public function map(callable $callback): self
return new self($items);
}

/**
* Run callback on each item of the collection an remove it if it does not return true
*
* @param callable $callback
* @return Collection
*/
public function filter(callable $callback): self
{
$items = array_filter($this->items, function ($item) use ($callback) {
return $callback($item);
});

return new self($items);
}

public function pushEach(array $data, ?callable $callback = null): CollectionInterface
{
if (! is_iterable($data)) {
Expand Down
10 changes: 10 additions & 0 deletions tests/CollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ public function testCount()
$this->assertEquals(3, count($collection));
}

public function testFilter()
{
$collection = new Collection(['foo', 'bar', 'baz']);
$this->assertEquals(3, $collection->count());
$collection = $collection->filter(function ($text) {
return substr($text, 0, 1) == 'b';
});
$this->assertEquals(2, $collection->count());
}

public function testFirstLast()
{
$collection = new Collection(['foo', 'bar', 'baz']);
Expand Down

0 comments on commit 7577986

Please sign in to comment.