Binary Search With Boundaries

Search a sorted array in logarithmic time, returning the index of a match or the insertion point when the value is absent.

JavascriptData Integrity

Code

snippet
export function binarySearch(sorted, target, compare = (a, b) => a - b) {
  let low = 0;
  let high = sorted.length;
  while (low < high) {
    const mid = (low + high) >>> 1;
    const cmp = compare(sorted[mid], target);
    if (cmp < 0) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  const found = low < sorted.length && compare(sorted[low], target) === 0;
  return { index: low, found };
}