binarySearchBy method

Result<int, int> binarySearchBy(
  1. int comparator(
    1. T
    )
)

Binary searches this slice with a comparator function. See SliceOnComparableSliceExtension.binarySearch for more.

Implementation

Result<int, int> binarySearchBy(int Function(T) comparator) {
  int left = 0;
  int right = this.length - 1;

  while (left <= right) {
    int mid = left + ((right - left) >> 1);
    int comp = comparator(getUnchecked(mid));

    if (comp == 0) {
      return Ok(mid);
    } else if (comp < 0) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  // If not found, return the index where it can be inserted to maintain sorted order.
  return Err(left);
}