bisectCenter<T extends Comparable<Object>> function

int bisectCenter<T extends Comparable<Object>>(
  1. List<T> list,
  2. T value, {
  3. int lo = 0,
  4. int? hi,
})

Returns the index of the closest element to value in list. Returns -1 if the list is empty.

Implementation

int bisectCenter<T extends Comparable<Object>>(
  List<T> list,
  T value, {
  int lo = 0,
  int? hi,
}) {
  final hiValue = hi ?? list.length;

  if (lo >= hiValue) return -1;

  final i = bisectLeft(list, value, lo: lo, hi: hiValue);

  if (i == 0) return 0;
  if (i == hiValue) return hiValue - 1;

  // Compare distances to left and right neighbors
  final left = list[i - 1];
  final right = list[i];

  // This is approximate for non-numeric types
  if (value.compareTo(left) == value.compareTo(right)) {
    return i;
  }

  return i - 1;
}