UNPKG

1.53 kBJavaScriptView Raw
1import { wrapWithAbort } from './operators/withabort';
2import { throwIfAborted } from '../aborterror';
3/**
4 * Returns the only element of an async-iterable sequence that matches the predicate if specified,
5 * or undefined if no such element exists; this method reports an exception if there is more
6 * than one element in the async-iterable sequence.
7 *
8 * @export
9 * @template T The type of the elements in the source sequence.
10 * @param {AsyncIterable<T>} source Source async-iterable sequence.
11 * @param {OptionalFindOptions<T>} [options] The optional options which includes a predicate for filtering,
12 * thisArg for predicate binding and an abort signal for cancellation.
13 * @returns {(Promise<T | undefined>)} A promise with the single element in the async-iterable sequence that satisfies
14 * the condition in the predicate, or undefined if no such element exists.
15 */
16export async function single(source, options) {
17 const { ['signal']: signal, ['thisArg']: thisArg, ['predicate']: predicate = async () => true } = options || {};
18 throwIfAborted(signal);
19 let result;
20 let hasResult = false;
21 let i = 0;
22 for await (const item of wrapWithAbort(source, signal)) {
23 if (hasResult && (await predicate.call(thisArg, item, i++, signal))) {
24 throw new Error('More than one element was found');
25 }
26 if (await predicate.call(thisArg, item, i++, signal)) {
27 result = item;
28 hasResult = true;
29 }
30 }
31 return result;
32}
33
34//# sourceMappingURL=single.mjs.map