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