averageBy method

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

Calculates the average of the selected values from all elements in the collection.

Applies the selector function to each element of the collection to obtain a numeric value and then computes the average of these values.

Parameters: selector (Function(T element)): A function that maps each element to a numeric value for averaging.

Returns: double: The average of the selected values from all elements in the collection.

Throws: StateError: If the collection is empty.

Example:

List<int> numbers = [1, 2, 3, 4, 5];
double result = numbers.averageBy((n) => n); // Output: 3.0

Note: The function throws a StateError if called on an empty collection, as an average cannot be calculated in this case.

Implementation

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

  for (var current in this) {
    sum += selector(current);
    count++;
  }

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

  return sum / count;
}