UNPKG

ix

Version:

The Interactive Extensions for JavaScript

50 lines (48 loc) 2.23 kB
import { __asyncValues, __awaiter } from "tslib"; import { wrapWithAbort } from './operators/withabort.mjs'; import { throwIfAborted } from '../aborterror.mjs'; /** * Returns the only element of an async-iterable sequence that matches the predicate if specified, * or undefined if no such element exists; this method reports an exception if there is more * than one element in the async-iterable sequence. * * @template T The type of the elements in the source sequence. * @param {AsyncIterable<T>} source Source async-iterable sequence. * @param {OptionalFindOptions<T>} [options] The optional options which includes a predicate for filtering, * thisArg for predicate binding and an abort signal for cancellation. * @returns {(Promise<T | undefined>)} A promise with the single element in the async-iterable sequence that satisfies * the condition in the predicate, or undefined if no such element exists. */ export function single(source, options) { var _a, e_1, _b, _c; return __awaiter(this, void 0, void 0, function* () { const { ['signal']: signal, ['thisArg']: thisArg, ['predicate']: predicate = () => __awaiter(this, void 0, void 0, function* () { return true; }) } = options || {}; throwIfAborted(signal); let result; let hasResult = false; let i = 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; if (hasResult && (yield predicate.call(thisArg, item, i++, signal))) { throw new Error('More than one element was found'); } if (yield predicate.call(thisArg, item, i++, signal)) { result = item; hasResult = true; } } } 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; } } return result; }); } //# sourceMappingURL=single.mjs.map