averageBy method

double averageBy(
  1. num selector(
    1. E element
    )
)

Returns the average of values returned by selector for all elements in the collection.

null values are counted as 0. Empty collections return null.

Implementation

double averageBy(num Function(E element) selector) {
  var count = 0;
  num sum = 0;

  for (var current in this) {
    var value = selector(current);
    if (value != null) {
      sum += value;
    }
    count++;
  }

  if (count == 0) {
    throw StateError('No elements in collection');
  } else {
    return sum / count;
  }
}