binaryIndex.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var binaryIndexBy = require('./binaryIndexBy'),
  2. identity = require('../utility/identity');
  3. /** Used as references for the maximum length and index of an array. */
  4. var MAX_ARRAY_LENGTH = 4294967295,
  5. HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
  6. /**
  7. * Performs a binary search of `array` to determine the index at which `value`
  8. * should be inserted into `array` in order to maintain its sort order.
  9. *
  10. * @private
  11. * @param {Array} array The sorted array to inspect.
  12. * @param {*} value The value to evaluate.
  13. * @param {boolean} [retHighest] Specify returning the highest qualified index.
  14. * @returns {number} Returns the index at which `value` should be inserted
  15. * into `array`.
  16. */
  17. function binaryIndex(array, value, retHighest) {
  18. var low = 0,
  19. high = array ? array.length : low;
  20. if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
  21. while (low < high) {
  22. var mid = (low + high) >>> 1,
  23. computed = array[mid];
  24. if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
  25. low = mid + 1;
  26. } else {
  27. high = mid;
  28. }
  29. }
  30. return high;
  31. }
  32. return binaryIndexBy(array, value, identity, retHighest);
  33. }
  34. module.exports = binaryIndex;