Skip to content

Instantly share code, notes, and snippets.

@en0
Created October 10, 2017 18:32
Show Gist options
  • Select an option

  • Save en0/90cdc823144416198d6b0df2e1c2165b to your computer and use it in GitHub Desktop.

Select an option

Save en0/90cdc823144416198d6b0df2e1c2165b to your computer and use it in GitHub Desktop.
Find the index of the closest or exact match in an ordered list.
function findClosest(haystack, needle, comp, lo, hi) {
var mid, cmp;
lo = lo || 0;
hi = hi || haystack.length - 1;
while(lo <= hi) {
mid = lo + (hi - lo>>1);
cmp = comp(haystack[mid], needle);
if(cmp < 0)
lo = mid + 1;
else if(cmp > 0)
hi = mid - 1;
else
return mid;
}
return lo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment