export function findNearestIndexOfValue()

in projects/inclusive_ai_a_chatgpt_plugin_and_dao_to_engage_marginalized_groups_in_ai/Inclusive.AI app/website/src/utils/misc.ts [83:99]


export function findNearestIndexOfValue(arr: number[], target: number): number {
  let left = 0
  let right = arr.length - 1

  while (left <= right) {
    const mid = Math.floor((left + right) / 2)

    if (arr[mid] === target) return mid
    else if (arr[mid] < target) left = mid + 1
    else right = mid - 1
  }

  // With two adjacent values for the target, return the element that is the nearest to the target
  return Math.abs(arr[left] - target) < Math.abs(arr[right] - target)
    ? left
    : right
}