ix
Version:
The Interactive Extensions for JavaScript
45 lines (43 loc) • 1.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.reduceRight = void 0;
const tslib_1 = require("tslib");
const toarray_js_1 = require("./toarray.js");
const aborterror_js_1 = require("../aborterror.js");
/**
* Applies an accumulator function over an async-iterable sequence from the end, 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 from the right.
* @param {ReduceOptions<T, R>} options The options which contains a callback, with optional seed and an optional abort signal for cancellation.
* @returns {Promise<R>} A promise with the final accumulator value.
*/
function reduceRight(source, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const { ['seed']: seed, ['signal']: signal, ['callback']: callback } = options;
const hasSeed = options.hasOwnProperty('seed');
(0, aborterror_js_1.throwIfAborted)(signal);
const array = yield (0, toarray_js_1.toArray)(source, signal);
let hasValue = false;
let acc = seed;
for (let offset = array.length - 1; offset >= 0; offset--) {
const item = array[offset];
if (hasValue || (hasValue = hasSeed)) {
acc = yield callback(acc, item, offset, signal);
}
else {
acc = item;
hasValue = true;
}
}
if (!(hasSeed || hasValue)) {
throw new Error('Sequence contains no elements');
}
return acc;
});
}
exports.reduceRight = reduceRight;
//# sourceMappingURL=reduceright.js.map