_baseSortedIndex.js 1.4 KB

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