1 | import { identity } from '../util/identity';
|
2 | /**
|
3 | * Computes the average of a sequence of values from the sequence either from the sequence itself
|
4 | * or from the selector function.
|
5 | * @example
|
6 | * // Using non chained version
|
7 | * const result = average([1, 2, 3]);
|
8 | * const result = Ix.Iterable.of(1, 2, 3).average();
|
9 | * console.log(result);
|
10 | * @param {Iterable<any>} source A sequence of values to calculate the average of.
|
11 | * @param {function(x: any): number} [selector] A transform function to apply to each element.
|
12 | * @returns {number} The average of the sequence of values.
|
13 | */
|
14 | export function average(source, selector = identity) {
|
15 | let sum = 0;
|
16 | let count = 0;
|
17 | for (const item of source) {
|
18 | sum += selector(item);
|
19 | count++;
|
20 | }
|
21 | if (count === 0) {
|
22 | throw new Error('Empty collection');
|
23 | }
|
24 | return sum / count;
|
25 | }
|
26 |
|
27 | //# sourceMappingURL=average.mjs.map
|