movingAverage method

double movingAverage([
  1. int? window
])

Calculates the moving average over the specified window.

Only works with numeric types (num, int, double). If window is null or larger than list length, uses all available elements. Returns 0.0 for empty lists or non-numeric types.

Example:

final prices = CircularList<double>(5)
  ..addAll([10.0, 11.0, 12.0, 13.0, 14.0]);
print(prices.movingAverage(3)); // average of last 3 prices

Implementation

double movingAverage([int? window]) {
  if (isEmpty) return 0.0;
  if (T == int || T == double || T == num) {
    final w = math.min(window ?? length, length);
    final start = math.max(0, length - w);
    var sum = 0.0;
    for (var i = start; i < length; i++) {
      sum += (this[i] as num);
    }
    return sum / w;
  }
  return 0.0;
}