median function
Returns the median of values, or null if the collection is empty.
For an even count, returns the average of the two middle values. Does not mutate the caller's input.
Example:
median([3, 1, 2]); // 2.0
median([4, 1, 2, 3]); // 2.5
Implementation
double? median(Iterable<num> values) {
// ignore: saropa_lints/avoid_large_list_copy -- needs an independent copy to sort without mutating the caller's input
final List<double> list = values.map((num n) => n.toDouble()).toList()..sort();
if (list.isEmpty) return null;
final int mid = list.length ~/ 2;
if (list.length.isOdd) return list[mid];
return (list[mid - 1] + list[mid]) / 2;
}