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.

55 lines
1.6 KiB

4 years ago
  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. /**
  7. * This method is like `_.find` except that it returns the index of the first
  8. * element `predicate` returns truthy for instead of the element itself.
  9. *
  10. * @static
  11. * @memberOf _
  12. * @since 1.1.0
  13. * @category Array
  14. * @param {Array} array The array to inspect.
  15. * @param {Function} [predicate=_.identity] The function invoked per iteration.
  16. * @param {number} [fromIndex=0] The index to search from.
  17. * @returns {number} Returns the index of the found element, else `-1`.
  18. * @example
  19. *
  20. * var users = [
  21. * { 'user': 'barney', 'active': false },
  22. * { 'user': 'fred', 'active': false },
  23. * { 'user': 'pebbles', 'active': true }
  24. * ];
  25. *
  26. * _.findIndex(users, function(o) { return o.user == 'barney'; });
  27. * // => 0
  28. *
  29. * // The `_.matches` iteratee shorthand.
  30. * _.findIndex(users, { 'user': 'fred', 'active': false });
  31. * // => 1
  32. *
  33. * // The `_.matchesProperty` iteratee shorthand.
  34. * _.findIndex(users, ['active', false]);
  35. * // => 0
  36. *
  37. * // The `_.property` iteratee shorthand.
  38. * _.findIndex(users, 'active');
  39. * // => 2
  40. */
  41. function findIndex(array, predicate, fromIndex) {
  42. var length = array == null ? 0 : array.length;
  43. if (!length) {
  44. return -1;
  45. }
  46. var index = fromIndex == null ? 0 : toInteger(fromIndex);
  47. if (index < 0) {
  48. index = nativeMax(length + index, 0);
  49. }
  50. return baseFindIndex(array, baseIteratee(predicate, 3), index);
  51. }
  52. module.exports = findIndex;