Binary Search Variant With Lower Bound (TypeScript)

Find the leftmost position where a sorted array can accept a target using a typed binary search lower bound variant.

TypescriptData Fetching

Code

snippet
function lowerBound<T>(arr: T[], target: T, cmp: (a: T, b: T) => number): number {
  let lo = 0, hi = arr.length;
  while (lo < hi) {
    const mid = (lo + hi) >>> 1;
    if (cmp(arr[mid], target) < 0) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

const arr = [1, 2, 2, 3, 4, 6];
console.log(lowerBound(arr, 2, (a, b) => a - b));