Frequencies<T>.fromMap constructor Null safety

Frequencies<T>.fromMap(
  1. Map<T, num> masses
)

Clones the map, normalizes the map values, and interprets the result as a distribution of observed values.

Implementation

factory Frequencies.fromMap(Map<T, num> masses) {
  if (masses.isEmpty) {
    return Frequencies._(<T, double>{});
  }
  var sum = 0.0;
  for (var m in masses.values) {
    if (m < 0.0) {
      throw ArgumentError.value(
          masses, 'masses', 'Found a negative probability');
    }
    sum += m;
  }
  if (sum == 0.0) {
    throw ArgumentError.value(
        masses, 'masses', 'Probabilities can not be all zero');
  }
  final result = <T, double>{};
  for (var entry in masses.entries) {
    result[entry.key] = entry.value / sum;
  }
  return Frequencies._(result);
}