reduce method

  1. @override
E reduce(
  1. E combine(
    1. E value,
    2. E element
    )
)
override

Reduces a collection to a single value by iteratively combining elements of the collection using the provided function.

The iterable must have at least one element. If it has only one element, that element is returned.

Otherwise this method starts with the first element from the iterator, and then combines it with the remaining elements in iteration order, as if by:

E value = iterable.first;
iterable.skip(1).forEach((element) {
  value = combine(value, element);
});
return value;

Example of calculating the sum of an iterable:

final numbers = <double>[10, 2, 5, 0.5];
final result = numbers.reduce((value, element) => value + element);
print(result); // 17.5

Consider using fold if the iterable can be empty.

Implementation

@override
E reduce(E Function(E value, E element) combine) {
  if (isEmpty) {
    throw _noElements();
  }
  var value = elementAt(0);
  for (var i = 1; i < length; i++) {
    value = combine(value, elementAt(i));
  }
  return value;
}