Skip to content

Function: slidingPair()

slidingPair<T>(): Operator<T, [undefined | T, T]>

Defined in: operators/slidingPair.ts:18

Creates a stream operator that emits pairs of values from the source stream, where each pair consists of the previous and the current value.

This operator is a powerful tool for comparing consecutive values in a stream. It maintains an internal state to remember the last value it received. For each new value, it creates a tuple of [previousValue, currentValue] and emits it to the output stream.

The very first value emitted will have undefined as its "previous" value.

Type Parameters

T

T = any

The type of the values in the source stream.

Returns

Operator<T, [undefined | T, T]>

An Operator instance that can be used in a stream's pipe method, emitting tuples of [T | undefined, T].

Examples

From slidingPair.spec.ts:5

typescript
const testStream = from([1, 2, 3, 4]);
const pairedStream = testStream.pipe(slidingPair());
const expectedValues = [
  [undefined, 1],
  [1, 2],
  [2, 3],
  [3, 4],
];
let index = 0;
pairedStream.subscribe({
  next: (value) => {
    expect(value).toEqual(expectedValues[index]);
    index++;
    if (index === expectedValues.length) {
      done();
    }
  },
  error: (err) => done.fail(err),
});

Released under the MIT License.