lastIndexOf.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var indexOfNaN = require('./_indexOfNaN'),
  2. toInteger = require('./toInteger');
  3. /* Built-in 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. * @since 0.1.0
  13. * @category Array
  14. * @param {Array} array The array to search.
  15. * @param {*} value The value to search for.
  16. * @param {number} [fromIndex=array.length-1] The index to search from.
  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. * // Search from the `fromIndex`.
  24. * _.lastIndexOf([1, 2, 1, 2], 2, 2);
  25. * // => 1
  26. */
  27. function lastIndexOf(array, value, fromIndex) {
  28. var length = array ? array.length : 0;
  29. if (!length) {
  30. return -1;
  31. }
  32. var index = length;
  33. if (fromIndex !== undefined) {
  34. index = toInteger(fromIndex);
  35. index = (
  36. index < 0
  37. ? nativeMax(length + index, 0)
  38. : nativeMin(index, length - 1)
  39. ) + 1;
  40. }
  41. if (value !== value) {
  42. return indexOfNaN(array, index - 1, true);
  43. }
  44. while (index--) {
  45. if (array[index] === value) {
  46. return index;
  47. }
  48. }
  49. return -1;
  50. }
  51. module.exports = lastIndexOf;