median property

double get median

Returns the median of the elements in this collection.

Empty collections throw an error.

Implementation

double get median {
  if (isEmpty) throw StateError("No elements");

  final sorted = toList()..sort();
  final size = sorted.length;
  final middleIdx = size ~/ 2;

  if (size.isOdd) {
    return sorted[middleIdx].toDouble();
  } else {
    final x = sorted[middleIdx];
    final y = sorted[middleIdx - 1];
    return (x + y) / 2;
  }
}