-
-
Save gostrafx/c76c905ea9caf17f3cd7847b82d8cda8 to your computer and use it in GitHub Desktop.
getBinarySearch() - Takes an array of values and returns a function that can be used to carry out the binary search on those values.
This file contains 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
/** | |
* Takes an array of values and returns a function that can be used to | |
* carry out the binary search on those values. The returned function | |
* takes one argument to indicate which direction the desired value may | |
* be found (send a negative number to look further back, a positive | |
* number to look further ahead or a `0` to return the same value as | |
* before). It doesn't matter what value you pass the first time you | |
* call the returned function. | |
* @template T | |
* @param {T[]} values | |
* @returns {(direction: number) => {index: number, value: T, values: T[]}} | |
*/ | |
function getBinarySearch(values) { | |
let index, min = 0, max = values.length - 1; | |
return function(direction) { | |
const isFirstRun = index === undefined; | |
if (isFirstRun) direction = 0; | |
if ((direction !== 0 && index >= 0) || isFirstRun) { | |
if (direction > 0) min = index + 1; | |
else if (direction < 0) max = index - 1; | |
index = min > max ? -1 : Math.floor((max + min) / 2); | |
} | |
return {index, value: values[index], values}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment