Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.8] Add countBy method to Collection #27770

Merged
merged 3 commits into from
Mar 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1890,6 +1890,28 @@ public function count()
return count($this->items);
}

/**
* Count the number of items in the collection by some predicate.
*
* @param callable|null
* @return static
*/
public function countBy($predicate = null)
{
if (is_null($predicate)) {
$predicate = function ($val) {
return $val;
};
}

return new static(
$this->groupBy($predicate)
->map(function ($val) {
return $val->count();
})
);
}

/**
* Add an item to the collection.
*
Expand Down
25 changes: 25 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,31 @@ public function testCountable()
$this->assertCount(2, $c);
}

public function testCountableByWithoutPredicate()
{
$c = new Collection(['foo', 'foo', 'foo', 'bar', 'bar', 'foobar']);
$this->assertEquals(['foo' => 3, 'bar' => 2, 'foobar' => 1], $c->countBy()->all());

$c = new Collection([true, true, false, false, false]);
$this->assertEquals([true => 2, false => 3], $c->countBy()->all());

$c = new Collection([1, 5, 1, 5, 5, 1]);
$this->assertEquals([1 => 3, 5 => 3], $c->countBy()->all());
}

public function testCountableByWithPredicate()
{
$c = new Collection(['alice', 'aaron', 'bob', 'carla']);
$this->assertEquals(['a' => 2, 'b' => 1, 'c' => 1], $c->countBy(function ($name) {
return substr($name, 0, 1);
})->all());

$c = new Collection([1, 2, 3, 4, 5]);
$this->assertEquals([true => 2, false => 3], $c->countBy(function ($i) {
return $i % 2 === 0;
})->all());
}

public function testIterable()
{
$c = new Collection(['foo']);
Expand Down