Skip to content

Instantly share code, notes, and snippets.

@MiguelCastillo
Last active February 13, 2018 15:44
Show Gist options
  • Save MiguelCastillo/e623a97f8bb8219c7fa43410432744c6 to your computer and use it in GitHub Desktop.
Save MiguelCastillo/e623a97f8bb8219c7fa43410432744c6 to your computer and use it in GitHub Desktop.
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