Binary Search Variant With Lower Bound (JavaScript)

Find the leftmost position where a sorted array can accept a target using binary search with a lower-bound variant that returns insertion index for duplicates.

JavascriptData Fetching

Code

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

const arr = [1, 2, 2, 3, 4, 6];
console.log(lowerBound(arr, 2)); // 1
console.log(lowerBound(arr, 5)); // 5