Created
October 10, 2017 18:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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