INNER CODE UNIT · JavaScript
closestIndex
sirius-ms/sirius · lcms2/viewer/viewer.js:23
let closestIndex = -1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const guess = functor(arr[mid]);
if (guess === target) {
return mid; // Target found, return its index
} else if (guess < target) {
low = mid + 1; // Target is in the right half
} else {
high = mid - 1; // Target is in the left half
}
// Update the closest index if needed
if (closestIndex === -1 || Math.abs(functor(arr[mid]) - target) < Math.abs(functor(arr[closestIndex]) - target)) {
closestIndex = mid;
}