Skip to content

Function: elementNth()

elementNth<T>(indexPattern): Operator<T, T>

Defined in: operators/elementNth.ts:24

Creates a stream operator that emits elements from the source stream at dynamic indices specified by the asynchronous index pattern function.

This operator is a powerful tool for selective data retrieval. It uses an indexPattern function to determine which elements to pull from the source stream. The function is called repeatedly, with the current iteration count as an argument, and should return the zero-based index of the next element to emit. The process stops when the function returns undefined.

This is useful for tasks such as:

  • Sampling a stream at a fixed interval (e.g., every 10th element).
  • Picking a specific, non-sequential set of elements.
  • Creating a custom, sparse output stream.

Type Parameters

T

T = any

The type of the values in the source stream.

Parameters

indexPattern

(iteration) => undefined | CallbackReturnType<number>

The function that specifies the indices to emit. It receives the current iteration count and should return the next index to emit or undefined to stop.

Returns

Operator<T, T>

An Operator instance that can be used in a stream's pipe method.

Examples

From elementNth.spec.ts:12

typescript
let subject: any = createSubject();

let source: any = subject;

const indexPattern = (iteration: number) =>
  iteration === 0 ? 0 : iteration === 1 ? 2 : undefined;
const nthStream = source.pipe(elementNth(indexPattern));
const results: any[] = [];
(async () => {
  for await (const value of eachValueFrom(nthStream)) {
    results.push(value);
  }
})();
subject.next(1);
subject.next(2);
subject.next(3);
subject.next(4);
subject.complete();
await new Promise((resolve) => setTimeout(resolve, 100));
expect(results).toEqual([1, 3]);

Released under the MIT License.