UNPKG

1.63 kBJavaScriptView Raw
1import { toArray } from './toarray';
2import { throwIfAborted } from '../aborterror';
3/**
4 * Applies an accumulator function over an async-iterable sequence from the end, 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 from the right.
12 * @param {ReduceOptions<T, R>} options The options which contains a callback, with optional seed and an optional abort signal for cancellation.
13 * @returns {Promise<R>} A promise with the final accumulator value.
14 */
15export async function reduceRight(source, options) {
16 const { ['seed']: seed, ['signal']: signal, ['callback']: callback } = options;
17 const hasSeed = options.hasOwnProperty('seed');
18 throwIfAborted(signal);
19 const array = await toArray(source, signal);
20 let hasValue = false;
21 let acc = seed;
22 for (let offset = array.length - 1; offset >= 0; offset--) {
23 const item = array[offset];
24 if (hasValue || (hasValue = hasSeed)) {
25 acc = await callback(acc, item, offset, signal);
26 }
27 else {
28 acc = item;
29 hasValue = true;
30 }
31 }
32 if (!(hasSeed || hasValue)) {
33 throw new Error('Sequence contains no elements');
34 }
35 return acc;
36}
37
38//# sourceMappingURL=reduceright.mjs.map