UNPKG

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