findLastIndex.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var baseFindIndex = require('./_baseFindIndex'),
  2. baseIteratee = require('./_baseIteratee'),
  3. toInteger = require('./toInteger');
  4. /* Built-in method references for those with the same name as other `lodash` methods. */
  5. var nativeMax = Math.max,
  6. nativeMin = Math.min;
  7. /**
  8. * This method is like `_.findIndex` except that it iterates over elements
  9. * of `collection` from right to left.
  10. *
  11. * @static
  12. * @memberOf _
  13. * @since 2.0.0
  14. * @category Array
  15. * @param {Array} array The array to search.
  16. * @param {Array|Function|Object|string} [predicate=_.identity]
  17. * The function invoked per iteration.
  18. * @param {number} [fromIndex=array.length-1] The index to search from.
  19. * @returns {number} Returns the index of the found element, else `-1`.
  20. * @example
  21. *
  22. * var users = [
  23. * { 'user': 'barney', 'active': true },
  24. * { 'user': 'fred', 'active': false },
  25. * { 'user': 'pebbles', 'active': false }
  26. * ];
  27. *
  28. * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
  29. * // => 2
  30. *
  31. * // The `_.matches` iteratee shorthand.
  32. * _.findLastIndex(users, { 'user': 'barney', 'active': true });
  33. * // => 0
  34. *
  35. * // The `_.matchesProperty` iteratee shorthand.
  36. * _.findLastIndex(users, ['active', false]);
  37. * // => 2
  38. *
  39. * // The `_.property` iteratee shorthand.
  40. * _.findLastIndex(users, 'active');
  41. * // => 0
  42. */
  43. function findLastIndex(array, predicate, fromIndex) {
  44. var length = array ? array.length : 0;
  45. if (!length) {
  46. return -1;
  47. }
  48. var index = length - 1;
  49. if (fromIndex !== undefined) {
  50. index = toInteger(fromIndex);
  51. index = fromIndex < 0
  52. ? nativeMax(length + index, 0)
  53. : nativeMin(index, length - 1);
  54. }
  55. return baseFindIndex(array, baseIteratee(predicate, 3), index, true);
  56. }
  57. module.exports = findLastIndex;