import { identityAsync } from '../util/identity.js'; import { wrapWithAbort } from './operators/withabort.js'; import { throwIfAborted } from '../aborterror.js'; import { MathOptions } from './mathoptions.js'; /** * Computes the average of the async-iterable sequence. * * @param {AsyncIterable} source The source async-iterable sequence to compute the average. * @param {AverageOptions} [options] The options for calculating the average. * @returns {Promise} A Promise which returns the computed average for the async-iterable sequence. */ export async function average( source: AsyncIterable, options?: MathOptions ): Promise; /** * Computes the average of the async-iterable sequence. * * @template TSource The type of elements in the source sequence. * @param {AsyncIterable} source source async-iterable sequence to compute the average. * @param {AverageOptions} [options] The options for calculating the average. * @returns {Promise} A Promise which returns the computed average for the async-iterable sequence. */ export async function average( source: AsyncIterable, options?: MathOptions ): Promise; /** * Computes the average of the async-iterable sequence. * * @param {AsyncIterable} source source async-iterable sequence to compute the average. * @param {AverageOptions} [options] The options for calculating the average. * @returns {Promise} A Promise which returns the computed average for the async-iterable sequence. */ export async function average( source: AsyncIterable, options?: MathOptions ): Promise { const { ['selector']: selector = identityAsync as any, ['signal']: signal, ['thisArg']: thisArg, } = options || {}; throwIfAborted(signal); let sum = 0; let count = 0; for await (const item of wrapWithAbort(source, signal)) { sum += await selector.call(thisArg, item, signal); count++; } if (count === 0) { throw new Error('Empty collection'); } return sum / count; }