You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.7 KiB

  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 inspect.
  16. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  17. * @param {number} [fromIndex=array.length-1] The index to search from.
  18. * @returns {number} Returns the index of the found element, else `-1`.
  19. * @example
  20. *
  21. * var users = [
  22. * { 'user': 'barney', 'active': true },
  23. * { 'user': 'fred', 'active': false },
  24. * { 'user': 'pebbles', 'active': false }
  25. * ];
  26. *
  27. * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
  28. * // => 2
  29. *
  30. * // The `_.matches` iteratee shorthand.
  31. * _.findLastIndex(users, { 'user': 'barney', 'active': true });
  32. * // => 0
  33. *
  34. * // The `_.matchesProperty` iteratee shorthand.
  35. * _.findLastIndex(users, ['active', false]);
  36. * // => 2
  37. *
  38. * // The `_.property` iteratee shorthand.
  39. * _.findLastIndex(users, 'active');
  40. * // => 0
  41. */
  42. function findLastIndex(array, predicate, fromIndex) {
  43. var length = array == null ? 0 : array.length;
  44. if (!length) {
  45. return -1;
  46. }
  47. var index = length - 1;
  48. if (fromIndex !== undefined) {
  49. index = toInteger(fromIndex);
  50. index = fromIndex < 0
  51. ? nativeMax(length + index, 0)
  52. : nativeMin(index, length - 1);
  53. }
  54. return baseFindIndex(array, baseIteratee(predicate, 3), index, true);
  55. }
  56. module.exports = findLastIndex;