includes.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var baseIndexOf = require('./_baseIndexOf'),
  2. isArrayLike = require('./isArrayLike'),
  3. isString = require('./isString'),
  4. toInteger = require('./toInteger'),
  5. values = require('./values');
  6. /* Built-in method references for those with the same name as other `lodash` methods. */
  7. var nativeMax = Math.max;
  8. /**
  9. * Checks if `value` is in `collection`. If `collection` is a string, it's
  10. * checked for a substring of `value`, otherwise
  11. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  12. * is used for equality comparisons. If `fromIndex` is negative, it's used as
  13. * the offset from the end of `collection`.
  14. *
  15. * @static
  16. * @memberOf _
  17. * @since 0.1.0
  18. * @category Collection
  19. * @param {Array|Object|string} collection The collection to inspect.
  20. * @param {*} value The value to search for.
  21. * @param {number} [fromIndex=0] The index to search from.
  22. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
  23. * @returns {boolean} Returns `true` if `value` is found, else `false`.
  24. * @example
  25. *
  26. * _.includes([1, 2, 3], 1);
  27. * // => true
  28. *
  29. * _.includes([1, 2, 3], 1, 2);
  30. * // => false
  31. *
  32. * _.includes({ 'a': 1, 'b': 2 }, 1);
  33. * // => true
  34. *
  35. * _.includes('abcd', 'bc');
  36. * // => true
  37. */
  38. function includes(collection, value, fromIndex, guard) {
  39. collection = isArrayLike(collection) ? collection : values(collection);
  40. fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
  41. var length = collection.length;
  42. if (fromIndex < 0) {
  43. fromIndex = nativeMax(length + fromIndex, 0);
  44. }
  45. return isString(collection)
  46. ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
  47. : (!!length && baseIndexOf(collection, value, fromIndex) > -1);
  48. }
  49. module.exports = includes;