UNPKG

1.55 kBJavaScriptView Raw
1import { wrapWithAbort } from './operators/withabort';
2import { throwIfAborted } from '../aborterror';
3/**
4 * Applies an accumulator function over an async-iterable sequence, returning the result of the aggregation as a
5 * single element in the result sequence. The seed value, if specified, is used as the initial accumulator value.
6 * For aggregation behavior with incremental intermediate results, scan.
7 *
8 * @export
9 * @template T The type of the elements in the source sequence.
10 * @template R The type of the result of the aggregation.
11 * @param {AsyncIterable<T>} source An async-iterable sequence to aggregate over.
12 * @param {ReduceOptions<T, R>} options The options which contains a callback, with optional seedn and an optional abort signal for cancellation.
13 * @returns {Promise<R>} A promise with the final accumulator value.
14 */
15export async function reduce(source, options) {
16 const { ['seed']: seed, ['signal']: signal, ['callback']: callback } = options;
17 const hasSeed = options.hasOwnProperty('seed');
18 throwIfAborted(signal);
19 let i = 0;
20 let hasValue = false;
21 let acc = seed;
22 for await (const item of wrapWithAbort(source, signal)) {
23 if (hasValue || (hasValue = hasSeed)) {
24 acc = await callback(acc, item, i++, signal);
25 }
26 else {
27 acc = item;
28 hasValue = true;
29 i++;
30 }
31 }
32 if (!(hasSeed || hasValue)) {
33 throw new Error('Sequence contains no elements');
34 }
35 return acc;
36}
37
38//# sourceMappingURL=reduce.mjs.map