indexOf.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var baseIndexOf = require('../internal/baseIndexOf'),
  2. binaryIndex = require('../internal/binaryIndex');
  3. /* Native method references for those with the same name as other `lodash` methods. */
  4. var nativeMax = Math.max;
  5. /**
  6. * Gets the index at which the first occurrence of `value` is found in `array`
  7. * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
  8. * for equality comparisons. If `fromIndex` is negative, it's used as the offset
  9. * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
  10. * performs a faster binary search.
  11. *
  12. * @static
  13. * @memberOf _
  14. * @category Array
  15. * @param {Array} array The array to search.
  16. * @param {*} value The value to search for.
  17. * @param {boolean|number} [fromIndex=0] The index to search from or `true`
  18. * to perform a binary search on a sorted array.
  19. * @returns {number} Returns the index of the matched value, else `-1`.
  20. * @example
  21. *
  22. * _.indexOf([1, 2, 1, 2], 2);
  23. * // => 1
  24. *
  25. * // using `fromIndex`
  26. * _.indexOf([1, 2, 1, 2], 2, 2);
  27. * // => 3
  28. *
  29. * // performing a binary search
  30. * _.indexOf([1, 1, 2, 2], 2, true);
  31. * // => 2
  32. */
  33. function indexOf(array, value, fromIndex) {
  34. var length = array ? array.length : 0;
  35. if (!length) {
  36. return -1;
  37. }
  38. if (typeof fromIndex == 'number') {
  39. fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
  40. } else if (fromIndex) {
  41. var index = binaryIndex(array, value);
  42. if (index < length &&
  43. (value === value ? (value === array[index]) : (array[index] !== array[index]))) {
  44. return index;
  45. }
  46. return -1;
  47. }
  48. return baseIndexOf(array, value, fromIndex || 0);
  49. }
  50. module.exports = indexOf;