fold<T> method

T fold <T>(
  1. T initialValue,
  2. T combine(
    1. T previousValue,
    2. T element
    )
)
inherited

Reduces a collection to a single value by iteratively combining each element of the collection with an existing value

Uses initialValue as the initial value, then iterates through the elements and updates the value with each element using the combine function, as if by:

var value = initialValue;
for (E element in this) {
  value = combine(value, element);
}
return value;

Example of calculating the sum of an iterable:

iterable.fold(0, (prev, element) => prev + element);

Implementation

T fold<T>(T initialValue, T combine(T previousValue, E element)) {
  var value = initialValue;
  int length = this.length;
  for (int i = 0; i < length; i++) {
    value = combine(value, this[i]);
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
  }
  return value;
}