Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function findInArray(items, value, predicate) {
predicate = predicate || contains;
var min = 0;
var max = items.length - 1;
var mid = Math.floor(items.length / 2);
var foundIndex = false;
while (foundIndex === false) {
if (predicate(items, value, min, mid)) {
foundIndex = items[min] === value ? min : items[mid] === value ? mid : false;
max = mid;
mid = Math.floor(mid / 2);
}
else if (predicate(items, value, mid, max)) {
foundIndex = items[mid] === value ? mid : items[max] === value ? max : false;
min = mid;
mid = Math.floor((max - min) / 2) + mid;
}
else {
return;
}
}
return foundIndex;
};
function contains(items, value, min, max) {
return value >= items[min] && value <= items[max];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.