bisectCenter function

int bisectCenter(
  1. List<num?> a,
  2. num? x, [
  3. int lo = 0,
  4. int? hi,
])

Returns the index of the numeric value closest to x in sorted a.

Implementation

int bisectCenter(List<num?> a, num? x, [int lo = 0, int? hi]) {
  final h = hi ?? a.length;
  final i = bisectLeft<num>(a, x, lo, h - 1);
  if (i <= lo || x == null) return i;
  final prev = a[i - 1];
  final curr = a[i];
  if (prev == null || curr == null) return i;
  final xd = x.toDouble();
  return (prev.toDouble() - xd) > -(curr.toDouble() - xd) ? i - 1 : i;
}