UNPKG

ix

Version:

The Interactive Extensions for JavaScript

54 lines (52 loc) 2.22 kB
import { __asyncValues, __awaiter } from "tslib"; import { wrapWithAbort } from './operators/withabort.mjs'; import { throwIfAborted } from '../aborterror.mjs'; /** * Applies an accumulator function over an async-iterable sequence, returning the result of the aggregation as a * single element in the result sequence. The seed value, if specified, is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, scan. * * @template T The type of the elements in the source sequence. * @template R The type of the result of the aggregation. * @param {AsyncIterable<T>} source An async-iterable sequence to aggregate over. * @param {ReduceOptions<T, R>} options The options which contains a callback, with optional seedn and an optional abort signal for cancellation. * @returns {Promise<R>} A promise with the final accumulator value. */ export function reduce(source, options) { var _a, e_1, _b, _c; return __awaiter(this, void 0, void 0, function* () { const { ['seed']: seed, ['signal']: signal, ['callback']: callback } = options; const hasSeed = options.hasOwnProperty('seed'); throwIfAborted(signal); let i = 0; let hasValue = false; let acc = seed; try { for (var _d = true, _e = __asyncValues(wrapWithAbort(source, signal)), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const item = _c; if (hasValue || (hasValue = hasSeed)) { acc = yield callback(acc, item, i++, signal); } else { acc = item; hasValue = true; i++; } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); } finally { if (e_1) throw e_1.error; } } if (!(hasSeed || hasValue)) { throw new Error('Sequence contains no elements'); } return acc; }); } //# sourceMappingURL=reduce.mjs.map