_binarySearch.js 537 B

1234567891011121314151617
  1. define(['./_getLength'], function (_getLength) {
  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. return binarySearch;
  14. });