Skip to content

Commit

Permalink
[10.x] Add percentage method to Collections (#48034)
Browse files Browse the repository at this point in the history
* Create percentage Collection method

* Update percentage to return null for empty collections and add more test cases

* formatting

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
WendellAdriel and taylorotwell committed Aug 11, 2023
1 parent 1eed738 commit e95dc82
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Illuminate/Collections/Traits/EnumeratesValues.php
Expand Up @@ -481,6 +481,25 @@ public function partition($key, $operator = null, $value = null)
return new static([new static($passed), new static($failed)]);
}

/**
* Calculate the percentage of items that pass a given truth test.
*
* @param (callable(TValue, TKey): bool) $callback
* @param int $precision
* @return float|null
*/
public function percentage(callable $callback, int $precision = 2)
{
if ($this->isEmpty()) {
return null;
}

return round(
$this->filter($callback)->count() / $this->count() * 100,
$precision
);
}

/**
* Get the sum of the given values.
*
Expand Down
41 changes: 41 additions & 0 deletions tests/Support/SupportCollectionTest.php
Expand Up @@ -5634,6 +5634,47 @@ public function testEnsureForInheritance($collection)
$data->ensure(\Throwable::class);
}

/**
* @dataProvider collectionClassProvider
*/
public function testPercentageWithFlatCollection($collection)
{
$collection = new $collection([1, 1, 2, 2, 2, 3]);

$this->assertSame(33.33, $collection->percentage(fn ($value) => $value === 1));
$this->assertSame(50.00, $collection->percentage(fn ($value) => $value === 2));
$this->assertSame(16.67, $collection->percentage(fn ($value) => $value === 3));
$this->assertSame(0.0, $collection->percentage(fn ($value) => $value === 5));
}

/**
* @dataProvider collectionClassProvider
*/
public function testPercentageWithNestedCollection($collection)
{
$collection = new $collection([
['name' => 'Taylor', 'foo' => 'foo'],
['name' => 'Nuno', 'foo' => 'bar'],
['name' => 'Dries', 'foo' => 'bar'],
['name' => 'Jess', 'foo' => 'baz'],
]);

$this->assertSame(25.00, $collection->percentage(fn ($value) => $value['foo'] === 'foo'));
$this->assertSame(50.00, $collection->percentage(fn ($value) => $value['foo'] === 'bar'));
$this->assertSame(25.00, $collection->percentage(fn ($value) => $value['foo'] === 'baz'));
$this->assertSame(0.0, $collection->percentage(fn ($value) => $value['foo'] === 'test'));
}

/**
* @dataProvider collectionClassProvider
*/
public function testPercentageReturnsNullForEmptyCollections($collection)
{
$collection = new $collection([]);

$this->assertNull($collection->percentage(fn ($value) => $value === 1));
}

/**
* Provides each collection class, respectively.
*
Expand Down

0 comments on commit e95dc82

Please sign in to comment.