Skip to content

Commit

Permalink
Fix PR based on feedback.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Mar 28, 2022
1 parent 294d556 commit c573d6f
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 10 deletions.
9 changes: 8 additions & 1 deletion docs/pages/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,14 @@ Signature: ``Collection::asyncMapN(callable ...$callbacks): Collection;``
averages
~~~~~~~~

Calculate the average of a list of numbers.
Calculate the average of a collection of numbers.

The average constitute the result obtained by adding together several amounts
and then dividing this total by the number of amounts.

Based on `scanLeft1`, this operation will return the average at each iteration.
Therefore, if you're looking for one single result, you must get the last item
using `last` operation.

Interface: `Averagesable`_

Expand Down
6 changes: 5 additions & 1 deletion docs/pages/code/operations/averages.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@
include __DIR__ . '/../../../../vendor/autoload.php';

$collection = Collection::fromIterable([1, 2, 3, 4, 5])
->averages(); // [1, 1.5, 2, 2.5, 3]
->averages(); // [1, 1.5, 2, 2.5, 3] from [1/1, (1+2)/2, (1+2+3)/3 ...]

$average = Collection::fromIterable([1, 2, 3, 4, 5])
->averages()
->last(); // [3]

$collection = Collection::empty()
->averages(); // []
10 changes: 9 additions & 1 deletion src/Contract/Operation/Averagesable.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,15 @@
interface Averagesable
{
/**
* Compute the averages.
* Calculate the average of a collection of numbers.
*
* The average constitute the result obtained by adding together several
* amounts and then dividing this total by the number of amounts.
*
* Based on `scanLeft1`, this operation will return the average at each
* iteration.
* Therefore, if you're looking for one single result, you must get the last
* item using `last` operation.
*
* @see https://loophp-collection.readthedocs.io/en/stable/pages/api.html#averages
*
Expand Down
8 changes: 1 addition & 7 deletions src/Operation/Averages.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,7 @@ public function __invoke(): Closure
return (new Pipe())()(
(new Normalize())(),
(new ScanLeft1())()(
/**
* @param float $acc
* @param float $value
*
* @return float
*/
static fn ($acc, $value, int $key) => ($acc * $key + $value) / ($key + 1)
static fn (float $acc, float $value, int $key): float => ($acc * $key + $value) / ($key + 1)
)
);
}
Expand Down

0 comments on commit c573d6f

Please sign in to comment.