UNPKG

2.22 kBJavaScriptView Raw
1var isSymbol = require('./isSymbol');
2
3/** Used as references for the maximum length and index of an array. */
4var MAX_ARRAY_LENGTH = 4294967295,
5 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1;
6
7/* Built-in method references for those with the same name as other `lodash` methods. */
8var nativeFloor = Math.floor,
9 nativeMin = Math.min;
10
11/**
12 * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
13 * which invokes `iteratee` for `value` and each element of `array` to compute
14 * their sort ranking. The iteratee is invoked with one argument; (value).
15 *
16 * @private
17 * @param {Array} array The sorted array to inspect.
18 * @param {*} value The value to evaluate.
19 * @param {Function} iteratee The iteratee invoked per element.
20 * @param {boolean} [retHighest] Specify returning the highest qualified index.
21 * @returns {number} Returns the index at which `value` should be inserted
22 * into `array`.
23 */
24function baseSortedIndexBy(array, value, iteratee, retHighest) {
25 value = iteratee(value);
26
27 var low = 0,
28 high = array == null ? 0 : array.length,
29 valIsNaN = value !== value,
30 valIsNull = value === null,
31 valIsSymbol = isSymbol(value),
32 valIsUndefined = value === undefined;
33
34 while (low < high) {
35 var mid = nativeFloor((low + high) / 2),
36 computed = iteratee(array[mid]),
37 othIsDefined = computed !== undefined,
38 othIsNull = computed === null,
39 othIsReflexive = computed === computed,
40 othIsSymbol = isSymbol(computed);
41
42 if (valIsNaN) {
43 var setLow = retHighest || othIsReflexive;
44 } else if (valIsUndefined) {
45 setLow = othIsReflexive && (retHighest || othIsDefined);
46 } else if (valIsNull) {
47 setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
48 } else if (valIsSymbol) {
49 setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
50 } else if (othIsNull || othIsSymbol) {
51 setLow = false;
52 } else {
53 setLow = retHighest ? (computed <= value) : (computed < value);
54 }
55 if (setLow) {
56 low = mid + 1;
57 } else {
58 high = mid;
59 }
60 }
61 return nativeMin(high, MAX_ARRAY_INDEX);
62}
63
64module.exports = baseSortedIndexBy;