@reactivex/ix-es5-esm
Version:
The Interactive Extensions for JavaScript
57 lines (55 loc) • 2.6 kB
JavaScript
import { __awaiter, __generator } from "tslib";
import { toArray } from './toarray.js';
import { throwIfAborted } from '../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.
*/
export function reduceRight(source, options) {
return __awaiter(this, void 0, void 0, function () {
var seed, signal, callback, hasSeed, array, hasValue, acc, offset, item;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
seed = options["seed"], signal = options["signal"], callback = options["callback"];
hasSeed = options.hasOwnProperty('seed');
throwIfAborted(signal);
return [4 /*yield*/, toArray(source, signal)];
case 1:
array = _a.sent();
hasValue = false;
acc = seed;
offset = array.length - 1;
_a.label = 2;
case 2:
if (!(offset >= 0)) return [3 /*break*/, 6];
item = array[offset];
if (!(hasValue || (hasValue = hasSeed))) return [3 /*break*/, 4];
return [4 /*yield*/, callback(acc, item, offset, signal)];
case 3:
acc = _a.sent();
return [3 /*break*/, 5];
case 4:
acc = item;
hasValue = true;
_a.label = 5;
case 5:
offset--;
return [3 /*break*/, 2];
case 6:
if (!(hasSeed || hasValue)) {
throw new Error('Sequence contains no elements');
}
return [2 /*return*/, acc];
}
});
});
}
//# sourceMappingURL=reduceright.js.map