causaltrack
Version:
vectors for causality tracking, whether characterizing or semantic causalities
39 lines (34 loc) • 1.1 kB
JavaScript
function binaryIndexOf(){
/**
* \from: [https://gist.github.com/Wolfy87/5734530]
* Performs a binary search on the host array. This method can either be
* injected into Array.prototype or called with a specified scope like this:
* binaryIndexOf.call(someArray, searchElement);
*
*
* @param {*} searchElement The item to search for within the array.
* @return {Number} The index of the element which defaults to -1 when not
* found.
*/
Array.prototype.binaryIndexOf = function(searchElement) {
var minIndex = 0;
var maxIndex = this.length - 1;
var currentIndex;
var currentElement;
while (minIndex <= maxIndex) {
currentIndex = Math.floor((minIndex + maxIndex) / 2);
currentElement = this[currentIndex];
if (currentElement.compare(searchElement) < 0) {
minIndex = currentIndex + 1;
}
else if (currentElement.compare(searchElement) > 0) {
maxIndex = currentIndex - 1;
}
else {
return currentIndex;
}
};
return ~maxIndex;
};
}
module.exports = binaryIndexOf();