UNPKG

1.33 kBJavaScriptView Raw
1import { equalityComparerAsync } from '../util/comparer';
2import { identityAsync } from '../util/identity';
3import { wrapWithAbort } from './operators/withabort';
4import { throwIfAborted } from '../aborterror';
5/**
6 * Returns the maximum element with the optional selector.
7 *
8 * @export
9 * @template TSource The type of the elements in the source sequence.
10 * @param {AsyncIterable<TSource>} source An async-iterable sequence to determine the maximum element of.
11 * @param {ExtremaByOptions<TKey>} [options] The options which include an optional comparer and abort signal.
12 * @returns {Promise<TResult>} The maximum element.
13 */
14export async function max(source, options) {
15 const { ['comparer']: comparer = equalityComparerAsync, ['signal']: signal, ['selector']: selector = identityAsync, } = options || {};
16 throwIfAborted(signal);
17 const it = wrapWithAbort(source, signal)[Symbol.asyncIterator]();
18 let next = await it.next();
19 if (next.done) {
20 throw new Error('Sequence contains no elements');
21 }
22 let maxValue = await selector(next.value);
23 while (!(next = await it.next()).done) {
24 const current = await selector(next.value);
25 if ((await comparer(current, maxValue)) > 0) {
26 maxValue = current;
27 }
28 }
29 return maxValue;
30}
31
32//# sourceMappingURL=max.mjs.map