UNPKG

@reactivex/ix-es5-esm

Version:

The Interactive Extensions for JavaScript

85 lines (83 loc) 3.89 kB
import { __asyncValues, __awaiter, __generator } from "tslib"; import { wrapWithAbort } from './operators/withabort.js'; import { throwIfAborted } from '../aborterror.js'; /** * 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 () { var _d, signal, thisArg, _e, predicate, result, hasResult, i, _f, _g, _h, item, _j, e_1_1; var _this = this; return __generator(this, function (_k) { switch (_k.label) { case 0: _d = options || {}, signal = _d["signal"], thisArg = _d["thisArg"], _e = _d["predicate"], predicate = _e === void 0 ? function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, true]; }); }); } : _e; throwIfAborted(signal); hasResult = false; i = 0; _k.label = 1; case 1: _k.trys.push([1, 9, 10, 15]); _f = true, _g = __asyncValues(wrapWithAbort(source, signal)); _k.label = 2; case 2: return [4 /*yield*/, _g.next()]; case 3: if (!(_h = _k.sent(), _a = _h.done, !_a)) return [3 /*break*/, 8]; _c = _h.value; _f = false; item = _c; _j = hasResult; if (!_j) return [3 /*break*/, 5]; return [4 /*yield*/, predicate.call(thisArg, item, i++, signal)]; case 4: _j = (_k.sent()); _k.label = 5; case 5: if (_j) { throw new Error('More than one element was found'); } return [4 /*yield*/, predicate.call(thisArg, item, i++, signal)]; case 6: if (_k.sent()) { result = item; hasResult = true; } _k.label = 7; case 7: _f = true; return [3 /*break*/, 2]; case 8: return [3 /*break*/, 15]; case 9: e_1_1 = _k.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 15]; case 10: _k.trys.push([10, , 13, 14]); if (!(!_f && !_a && (_b = _g.return))) return [3 /*break*/, 12]; return [4 /*yield*/, _b.call(_g)]; case 11: _k.sent(); _k.label = 12; case 12: return [3 /*break*/, 14]; case 13: if (e_1) throw e_1.error; return [7 /*endfinally*/]; case 14: return [7 /*endfinally*/]; case 15: return [2 /*return*/, result]; } }); }); } //# sourceMappingURL=single.js.map