Skip to content

Instantly share code, notes, and snippets.

@gostrafx
Forked from westc/getBinarySearch.js
Created March 27, 2023 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gostrafx/c76c905ea9caf17f3cd7847b82d8cda8 to your computer and use it in GitHub Desktop.
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.
/**
* 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