pairsWith<T, R> function Transforming data

List<R> pairsWith<T, R>(
  1. Iterable<T> iterable,
  2. R reducer(
    1. T,
    2. T
    )
)

Returns a list of values yielded by the reducer function applied to each pair of consecutive elements from the provided iterable.

For example:

pairsWith([1, 2, 3, 4], (a, b) => b - a); returns [1, 1, 1];

If the specified iterable has fewer than two elements, returns the empty list.

Implementation

List<R> pairsWith<T, R>(Iterable<T> iterable, R Function(T, T) reducer) {
  final pairs = <R>[];
  late T previous;
  var first = false;
  for (final value in iterable) {
    if (first) pairs.add(reducer(previous, value));
    previous = value;
    first = true;
  }
  return pairs;
}