UNPKG

1.09 kBJavaScriptView Raw
1import { wrapWithAbort } from './operators/withabort';
2import { throwIfAborted } from '../aborterror';
3/**
4 * Returns the element at a specified index in a sequence or undefined if the index is out of range.
5 *
6 * @export
7 * @template T The type of the elements in the source sequence.
8 * @param {AsyncIterable<T>} source async-iterable sequence to return the element from.
9 * @param {number} index The zero-based index of the element to retrieve.
10 * @param {AbortSignal} [signal] The optional abort signal to be used for cancelling the sequence at any time.
11 * @returns {(Promise<T | undefined>)} An async-iterable sequence that produces the element at the specified
12 * position in the source sequence, or undefined if the index is outside the bounds of the source sequence.
13 */
14export async function elementAt(source, index, signal) {
15 throwIfAborted(signal);
16 let i = index;
17 for await (const item of wrapWithAbort(source, signal)) {
18 if (i === 0) {
19 return item;
20 }
21 i--;
22 }
23 return undefined;
24}
25
26//# sourceMappingURL=elementat.mjs.map