Skip to content

Commit

Permalink
[11.x] Collection average/avg optimization (#51512)
Browse files Browse the repository at this point in the history
* optimize avg

* styleci

* formatting

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
bert-w and taylorotwell authored May 20, 2024
1 parent bf7046f commit 3b70842
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 30 deletions.
19 changes: 0 additions & 19 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,25 +75,6 @@ public function lazy()
return new LazyCollection($this->items);
}

/**
* Get the average value of a given key.
*
* @param (callable(TValue): float|int)|string|null $callback
* @return float|int|null
*/
public function avg($callback = null)
{
$callback = $this->valueRetriever($callback);

$items = $this
->map(fn ($value) => $callback($value))
->filter(fn ($value) => ! is_null($value));

if ($count = $items->count()) {
return $items->sum() / $count;
}
}

/**
* Get the median of a given key.
*
Expand Down
11 changes: 0 additions & 11 deletions src/Illuminate/Collections/LazyCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,17 +154,6 @@ public function remember()
});
}

/**
* Get the average value of a given key.
*
* @param (callable(TValue): float|int)|string|null $callback
* @return float|int|null
*/
public function avg($callback = null)
{
return $this->collect()->avg($callback);
}

/**
* Get the median of a given key.
*
Expand Down
22 changes: 22 additions & 0 deletions src/Illuminate/Collections/Traits/EnumeratesValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,28 @@ public static function times($number, ?callable $callback = null)
->map($callback);
}

/**
* Get the average value of a given key.
*
* @param (callable(TValue): float|int)|string|null $callback
* @return float|int|null
*/
public function avg($callback = null)
{
$callback = $this->valueRetriever($callback);

$reduced = $this->reduce(static function (&$reduce, $value) use ($callback) {
if (! is_null($resolved = $callback($value))) {
$reduce[0] += $resolved;
$reduce[1]++;
}

return $reduce;
}, [0, 0]);

return $reduced[1] ? $reduced[0] / $reduced[1] : null;
}

/**
* Alias for the "avg" method.
*
Expand Down
3 changes: 3 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4076,6 +4076,9 @@ public function testGettingAvgItemsFromCollection($collection)
(object) ['foo' => 6],
]);
$this->assertEquals(3, $c->avg('foo'));

$c = new $collection([0]);
$this->assertEquals(0, $c->avg());
}

#[DataProvider('collectionClassProvider')]
Expand Down

0 comments on commit 3b70842

Please sign in to comment.