UNPKG

1.22 kBJavaScriptView Raw
1import { wrapWithAbort } from './operators/withabort';
2import { throwIfAborted } from '../aborterror';
3/**
4 * Returns the last element of an async-iterable sequence that satisfies the condition in the predicate if given
5 * otherwise the last item in the sequence, or a default value if no such element exists.
6 *
7 * @export
8 * @template T The type of elements in the source sequence.
9 * @param {AsyncIterable<T>} source The source async-iterable sequence.
10 * @param {OptionalFindOptions<T, S>} [options] The options which include an optional predicate for filtering,
11 * thirArg for binding, and abort signal for cancellation
12 * @returns {(Promise<S | undefined>)} A promise containing the last value that matches the optional predicate or last item, otherwise undefined.
13 */
14export async function last(source, options) {
15 const { ['signal']: signal, ['thisArg']: thisArg, ['predicate']: predicate = async () => true } = options || {};
16 throwIfAborted(signal);
17 let i = 0;
18 let result;
19 for await (const item of wrapWithAbort(source, signal)) {
20 if (await predicate.call(thisArg, item, i++, signal)) {
21 result = item;
22 }
23 }
24 return result;
25}
26
27//# sourceMappingURL=last.mjs.map