Skip to content

Commit 63a50d3

Browse files
committed
Re-use createAggregator for Collection.countBy function
1 parent 7dd9fb4 commit 63a50d3

File tree

2 files changed

+11
-19
lines changed

2 files changed

+11
-19
lines changed

src/Collection/countBy.php

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
namespace _;
1313

14+
use function _\internal\createAggregator;
15+
1416
/**
1517
* Creates an array composed of keys generated from the results of running
1618
* each element of `collection` through `iteratee`. The corresponding value of
@@ -33,27 +35,15 @@
3335
* // => ['3' => 2, '5' => 1]
3436
* </code>
3537
*/
36-
function countBy(iterable $collection, callable $iteratee = null): array
38+
function countBy(iterable $collection, callable $iteratee): array
3739
{
38-
if (!$iteratee) {
39-
$iteratee = '_\identity';
40-
}
41-
42-
$result = [];
43-
44-
foreach ($collection as $value) {
45-
if (!\is_scalar($value)) {
46-
continue;
40+
return createAggregator(function ($result, $key, $value) {
41+
if (!isset($result[$value])) {
42+
$result[$value] = 0;
4743
}
4844

49-
$computed = $iteratee($value);
50-
51-
if (!isset($result[$computed])) {
52-
$result[$computed] = 0;
53-
};
54-
55-
$result[$computed]++;
56-
}
45+
$result[$value]++;
5746

58-
return $result;
47+
return $result;
48+
})($collection, $iteratee);
5949
}

src/Collection/groupBy.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
namespace _;
1313

14+
use function _\internal\createAggregator;
15+
1416
/**
1517
* Creates an array composed of keys generated from the results of running
1618
* each element of `collection` through `iteratee`. The order of grouped values

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy