UNPKG

1.17 kBJavaScriptView Raw
1import { wrapWithAbort } from './operators/withabort';
2import { throwIfAborted } from '../aborterror';
3/**
4 * Returns a promise that represents how many elements in the specified async-iterable sequence satisfy a condition
5 * otherwise, the number of items in the sequence.
6 *
7 * @export
8 * @template T The type of elements in the source collection.
9 * @param {AsyncIterable<T>} source An async-iterable sequence that contains elements to be counted.
10 * @param {OptionalFindOptions<T>} [options] The options for a predicate for filtering, thisArg for binding and AbortSignal for cancellation.
11 * @returns {Promise<number>} The number of matching elements for the given condition if provided, otherwise
12 * the number of elements in the sequence.
13 */
14export async function count(source, options) {
15 const { ['signal']: signal, ['thisArg']: thisArg, ['predicate']: predicate = async () => true } = options || {};
16 throwIfAborted(signal);
17 let i = 0;
18 for await (const item of wrapWithAbort(source, signal)) {
19 if (await predicate.call(thisArg, item, i, signal)) {
20 i++;
21 }
22 }
23 return i;
24}
25
26//# sourceMappingURL=count.mjs.map