_binarySearch.js 514 B

123456789101112131415
  1. var _getLength = require('./_getLength.js');
  2. // Iteratively cut `array` in half to figure out the index at which `obj` should
  3. // be inserted so as to maintain the order defined by `compare`.
  4. function binarySearch(array, obj, iteratee, compare) {
  5. var value = iteratee(obj);
  6. var low = 0, high = _getLength(array);
  7. while (low < high) {
  8. var mid = Math.floor((low + high) / 2);
  9. if (compare(iteratee(array[mid]), value)) low = mid + 1; else high = mid;
  10. }
  11. return low;
  12. }
  13. module.exports = binarySearch;