pairwise()

Iterates stream source and yields paired keys and values from previous iteration and current iteration.

If stream source has less than two elements, the stream will be empty.

class RunOpenCode\Component\Dataset\Operator\Pairwise
__construct(iterable<TKey, TValue> $source
Parameters:
  • $source – iterable<TKey, TValue> Stream source to iterate over.

getIterator()
Returns:

\Traversable<array{TKey, TKey}, array{TValue, TValue}> Stream containing paired keys and values from previous and current iteration.

Use cases

  • Combine previous and current iteration values to calculate delta between two iterations.

Example

Combine sequence of transactions to yield deltas.

 1<?php
 2
 3use RunOpenCode\Component\Dataset\Stream;
 4
 5$transactions = $connection->execute('SELECT ...');
 6
 7new Stream($transactions)
 8    ->pairwise()
 9    ->map(function (array $previous, array $current): array {
10        return [
11             'delta' => $current['amount'] - $previous['amount'],
12             'previous' => $previous,
13             'current' => $current,
14        ];
15    })