averageBy<N extends num> method

double averageBy<N extends num>(
  1. N mapper(
    1. T element
    )
)

The arithmetic mean of the elements of a non-empty iterable. The arithmetic mean is the sum of the elements divided by the number of elements. If iterable is empty it returns 0. Examples:

expect([1, 2, 3, 4, 5].averageBy((e) => e), 3.0);
expect([1.5, 2.5, 3.3, 4, 5].averageBy((e) => e), 3.26);
expect(['a', 'ab', 'abc', 'abcd', 'abcde'].sumBy((e) => e.length), 3.0);

Implementation

double averageBy<N extends num>(N Function(T element) mapper) {
  double result = 0.0;
  var count = 0;
  for (final value in this) {
    count += 1;
    result += (mapper(value) - result) / count;
  }
  return result;
}