UNPKG

ix

Version:

The Interactive Extensions for JavaScript

35 lines (33 loc) 1.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.single = void 0; /** * Returns the only element of an 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 iterable sequence. * * @template T The type of the elements in the source sequence. * @param {AsyncIterable<T>} source Source iterable sequence. * @param {OptionalFindOptions<T>} [options] The optional options which includes a predicate for filtering, * and thisArg for predicate binding. * @returns {(T | undefined)} The single element in the iterable sequence that satisfies * the condition in the predicate, or undefined if no such element exists. */ function single(source, options) { const { ['thisArg']: thisArg, ['predicate']: predicate = () => true } = options || {}; let result; let hasResult = false; let i = 0; for (const item of source) { if (hasResult && predicate.call(thisArg, item, i++)) { throw new Error('More than one element was found'); } if (predicate.call(thisArg, item, i++)) { result = item; hasResult = true; } } return result; } exports.single = single; //# sourceMappingURL=single.js.map