Skip to content

Commit 3b70842

Browse files
bert-wtaylorotwell
andauthored
[11.x] Collection average/avg optimization (#51512)
* optimize avg * styleci * formatting --------- Co-authored-by: Taylor Otwell <taylor@laravel.com>
1 parent bf7046f commit 3b70842

File tree

4 files changed

+25
-30
lines changed

4 files changed

+25
-30
lines changed

src/Illuminate/Collections/Collection.php

-19
Original file line numberDiff line numberDiff line change
@@ -75,25 +75,6 @@ public function lazy()
7575
return new LazyCollection($this->items);
7676
}
7777

78-
/**
79-
* Get the average value of a given key.
80-
*
81-
* @param (callable(TValue): float|int)|string|null $callback
82-
* @return float|int|null
83-
*/
84-
public function avg($callback = null)
85-
{
86-
$callback = $this->valueRetriever($callback);
87-
88-
$items = $this
89-
->map(fn ($value) => $callback($value))
90-
->filter(fn ($value) => ! is_null($value));
91-
92-
if ($count = $items->count()) {
93-
return $items->sum() / $count;
94-
}
95-
}
96-
9778
/**
9879
* Get the median of a given key.
9980
*

src/Illuminate/Collections/LazyCollection.php

-11
Original file line numberDiff line numberDiff line change
@@ -154,17 +154,6 @@ public function remember()
154154
});
155155
}
156156

157-
/**
158-
* Get the average value of a given key.
159-
*
160-
* @param (callable(TValue): float|int)|string|null $callback
161-
* @return float|int|null
162-
*/
163-
public function avg($callback = null)
164-
{
165-
return $this->collect()->avg($callback);
166-
}
167-
168157
/**
169158
* Get the median of a given key.
170159
*

src/Illuminate/Collections/Traits/EnumeratesValues.php

+22
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,28 @@ public static function times($number, ?callable $callback = null)
175175
->map($callback);
176176
}
177177

178+
/**
179+
* Get the average value of a given key.
180+
*
181+
* @param (callable(TValue): float|int)|string|null $callback
182+
* @return float|int|null
183+
*/
184+
public function avg($callback = null)
185+
{
186+
$callback = $this->valueRetriever($callback);
187+
188+
$reduced = $this->reduce(static function (&$reduce, $value) use ($callback) {
189+
if (! is_null($resolved = $callback($value))) {
190+
$reduce[0] += $resolved;
191+
$reduce[1]++;
192+
}
193+
194+
return $reduce;
195+
}, [0, 0]);
196+
197+
return $reduced[1] ? $reduced[0] / $reduced[1] : null;
198+
}
199+
178200
/**
179201
* Alias for the "avg" method.
180202
*

tests/Support/SupportCollectionTest.php

+3
Original file line numberDiff line numberDiff line change
@@ -4076,6 +4076,9 @@ public function testGettingAvgItemsFromCollection($collection)
40764076
(object) ['foo' => 6],
40774077
]);
40784078
$this->assertEquals(3, $c->avg('foo'));
4079+
4080+
$c = new $collection([0]);
4081+
$this->assertEquals(0, $c->avg());
40794082
}
40804083

40814084
#[DataProvider('collectionClassProvider')]

0 commit comments

Comments
 (0)