includes.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var baseIndexOf = require('../internal/baseIndexOf'),
  2. getLength = require('../internal/getLength'),
  3. isArray = require('../lang/isArray'),
  4. isIterateeCall = require('../internal/isIterateeCall'),
  5. isLength = require('../internal/isLength'),
  6. isString = require('../lang/isString'),
  7. values = require('../object/values');
  8. /* Native method references for those with the same name as other `lodash` methods. */
  9. var nativeMax = Math.max;
  10. /**
  11. * Checks if `target` is in `collection` using
  12. * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
  13. * for equality comparisons. If `fromIndex` is negative, it's used as the offset
  14. * from the end of `collection`.
  15. *
  16. * @static
  17. * @memberOf _
  18. * @alias contains, include
  19. * @category Collection
  20. * @param {Array|Object|string} collection The collection to search.
  21. * @param {*} target The value to search for.
  22. * @param {number} [fromIndex=0] The index to search from.
  23. * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
  24. * @returns {boolean} Returns `true` if a matching element is found, else `false`.
  25. * @example
  26. *
  27. * _.includes([1, 2, 3], 1);
  28. * // => true
  29. *
  30. * _.includes([1, 2, 3], 1, 2);
  31. * // => false
  32. *
  33. * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
  34. * // => true
  35. *
  36. * _.includes('pebbles', 'eb');
  37. * // => true
  38. */
  39. function includes(collection, target, fromIndex, guard) {
  40. var length = collection ? getLength(collection) : 0;
  41. if (!isLength(length)) {
  42. collection = values(collection);
  43. length = collection.length;
  44. }
  45. if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
  46. fromIndex = 0;
  47. } else {
  48. fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
  49. }
  50. return (typeof collection == 'string' || !isArray(collection) && isString(collection))
  51. ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1)
  52. : (!!length && baseIndexOf(collection, target, fromIndex) > -1);
  53. }
  54. module.exports = includes;