UNPKG

1.02 kBJavaScriptView Raw
1import { identityAsync } from '../util/identity';
2import { wrapWithAbort } from './operators/withabort';
3import { throwIfAborted } from '../aborterror';
4/**
5 * Computes the average of the async-iterable sequence.
6 *
7 * @export
8 * @param {AsyncIterable<any>} source source async-iterable sequence to compute the average.
9 * @param {AverageOptions<any>} [options] The options for calculating the average.
10 * @returns {Promise<number>} A Promise which returns the computed average for the async-iterable sequence.
11 */
12export async function average(source, options) {
13 const { ['selector']: selector = identityAsync, ['signal']: signal, ['thisArg']: thisArg, } = options || {};
14 throwIfAborted(signal);
15 let sum = 0;
16 let count = 0;
17 for await (const item of wrapWithAbort(source, signal)) {
18 sum += await selector.call(thisArg, item, signal);
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