binaryIndexBy.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* Native method references for those with the same name as other `lodash` methods. */
  2. var nativeFloor = Math.floor,
  3. nativeMin = Math.min;
  4. /** Used as references for the maximum length and index of an array. */
  5. var MAX_ARRAY_LENGTH = 4294967295,
  6. MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1;
  7. /**
  8. * This function is like `binaryIndex` except that it invokes `iteratee` for
  9. * `value` and each element of `array` to compute their sort ranking. The
  10. * iteratee is invoked with one argument; (value).
  11. *
  12. * @private
  13. * @param {Array} array The sorted array to inspect.
  14. * @param {*} value The value to evaluate.
  15. * @param {Function} iteratee The function invoked per iteration.
  16. * @param {boolean} [retHighest] Specify returning the highest qualified index.
  17. * @returns {number} Returns the index at which `value` should be inserted
  18. * into `array`.
  19. */
  20. function binaryIndexBy(array, value, iteratee, retHighest) {
  21. value = iteratee(value);
  22. var low = 0,
  23. high = array ? array.length : 0,
  24. valIsNaN = value !== value,
  25. valIsNull = value === null,
  26. valIsUndef = value === undefined;
  27. while (low < high) {
  28. var mid = nativeFloor((low + high) / 2),
  29. computed = iteratee(array[mid]),
  30. isDef = computed !== undefined,
  31. isReflexive = computed === computed;
  32. if (valIsNaN) {
  33. var setLow = isReflexive || retHighest;
  34. } else if (valIsNull) {
  35. setLow = isReflexive && isDef && (retHighest || computed != null);
  36. } else if (valIsUndef) {
  37. setLow = isReflexive && (retHighest || isDef);
  38. } else if (computed == null) {
  39. setLow = false;
  40. } else {
  41. setLow = retHighest ? (computed <= value) : (computed < value);
  42. }
  43. if (setLow) {
  44. low = mid + 1;
  45. } else {
  46. high = mid;
  47. }
  48. }
  49. return nativeMin(high, MAX_ARRAY_INDEX);
  50. }
  51. module.exports = binaryIndexBy;