lastIndexOf.js 1.6 KB

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