Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var binaryIndex = require('../internal/binaryIndex'),
2
indexOfNaN = require('../internal/indexOfNaN');
3
4
/* Native method references for those with the same name as other `lodash` methods. */
5
var nativeMax = Math.max,
6
nativeMin = Math.min;
7
8
/**
9
* This method is like `_.indexOf` except that it iterates over elements of
10
* `array` from right to left.
11
*
12
* @static
13
* @memberOf _
14
* @category Array
15
* @param {Array} array The array to search.
16
* @param {*} value The value to search for.
17
* @param {boolean|number} [fromIndex=array.length-1] The index to search from
18
* or `true` to perform a binary search on a sorted array.
19
* @returns {number} Returns the index of the matched value, else `-1`.
20
* @example
21
*
22
* _.lastIndexOf([1, 2, 1, 2], 2);
23
* // => 3
24
*
25
* // using `fromIndex`
26
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
27
* // => 1
28
*
29
* // performing a binary search
30
* _.lastIndexOf([1, 1, 2, 2], 2, true);
31
* // => 3
32
*/
33
function lastIndexOf(array, value, fromIndex) {
34
var length = array ? array.length : 0;
35
if (!length) {
36
return -1;
37
}
38
var index = length;
39
if (typeof fromIndex == 'number') {
40
index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
41
} else if (fromIndex) {
42
index = binaryIndex(array, value, true) - 1;
43
var other = array[index];
44
if (value === value ? (value === other) : (other !== other)) {
45
return index;
46
}
47
return -1;
48
}
49
if (value !== value) {
50
return indexOfNaN(array, index, true);
51
}
52
while (index--) {
53
if (array[index] === value) {
54
return index;
55
}
56
}
57
return -1;
58
}
59
60
module.exports = lastIndexOf;
61
62