ix
Version:
The Interactive Extensions for JavaScript
43 lines (41 loc) • 1.64 kB
JavaScript
import { __asyncValues, __awaiter } from "tslib";
import { identityAsync } from '../util/identity.mjs';
import { wrapWithAbort } from './operators/withabort.mjs';
import { throwIfAborted } from '../aborterror.mjs';
/**
* Computes the average of the async-iterable sequence.
*
* @param {AsyncIterable<any>} source source async-iterable sequence to compute the average.
* @param {AverageOptions<any>} [options] The options for calculating the average.
* @returns {Promise<number>} A Promise which returns the computed average for the async-iterable sequence.
*/
export function average(source, options) {
var _a, e_1, _b, _c;
return __awaiter(this, void 0, void 0, function* () {
const { ['selector']: selector = identityAsync, ['signal']: signal, ['thisArg']: thisArg, } = options || {};
throwIfAborted(signal);
let sum = 0;
let count = 0;
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;
sum += yield selector.call(thisArg, item, signal);
count++;
}
}
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 (count === 0) {
throw new Error('Empty collection');
}
return sum / count;
});
}
//# sourceMappingURL=average.mjs.map