findIndex.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 search.
  15. * @param {Array|Function|Object|string} [predicate=_.identity]
  16. * The function invoked per iteration.
  17. * @param {number} [fromIndex=0] 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': false },
  23. * { 'user': 'fred', 'active': false },
  24. * { 'user': 'pebbles', 'active': true }
  25. * ];
  26. *
  27. * _.findIndex(users, function(o) { return o.user == 'barney'; });
  28. * // => 0
  29. *
  30. * // The `_.matches` iteratee shorthand.
  31. * _.findIndex(users, { 'user': 'fred', 'active': false });
  32. * // => 1
  33. *
  34. * // The `_.matchesProperty` iteratee shorthand.
  35. * _.findIndex(users, ['active', false]);
  36. * // => 0
  37. *
  38. * // The `_.property` iteratee shorthand.
  39. * _.findIndex(users, 'active');
  40. * // => 2
  41. */
  42. function findIndex(array, predicate, fromIndex) {
  43. var length = array ? array.length : 0;
  44. if (!length) {
  45. return -1;
  46. }
  47. var index = fromIndex == null ? 0 : toInteger(fromIndex);
  48. if (index < 0) {
  49. index = nativeMax(length + index, 0);
  50. }
  51. return baseFindIndex(array, baseIteratee(predicate, 3), index);
  52. }
  53. module.exports = findIndex;