binByWidth function

List<int> binByWidth(
  1. List<num> values, {
  2. required num min,
  3. required num max,
  4. required int bins,
})

Assign each value in values to an equal-width bin over [min, max].

The range is split into bins intervals of equal width. Values below min clamp into bin 0 and values at or above max clamp into the last bin, so out-of-range data is never dropped or out of index. Result indices are in 0..bins-1. Audited: 2026-06-12 11:26 EDT

Implementation

List<int> binByWidth(
  List<num> values, {
  required num min,
  required num max,
  required int bins,
}) {
  // Enforced in release: `bins < 1` makes the width division `/ bins` divide by
  // zero (Infinity width → every value floors to bin 0), and `max <= min` makes
  // the width zero/negative — both silently wrong, not an error. Asserts strip.
  if (bins < 1) {
    throw ArgumentError.value(bins, 'bins', 'must be >= 1');
  }
  if (max <= min) {
    throw ArgumentError('binByWidth requires max ($max) > min ($min)');
  }
  final double width = (max - min) / bins;
  return values.map((num v) => _widthBin(v.toDouble(), min.toDouble(), width, bins)).toList();
}