sumBy<N extends num> method

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

The sum of the values returned by the mapper function.

Examples:

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

Implementation

N sumBy<N extends num>(N Function(T element) mapper) {
  // If the iterable is empty but N is double
  // then result will be an int because 0 is an int
  // therefore result as N (which in this case will be: 0 as double)
  // will throw an error
  if (isEmpty) {
    return _zeroOf<N>();
  }

  num result = 0;
  for (final value in this) {
    result = result + mapper(value);
  }
  return result as N;
}