mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-01-31 15:27:50 +00:00
61 lines
2.0 KiB
JavaScript
61 lines
2.0 KiB
JavaScript
import baseIndexOf from '../internal/baseIndexOf';
|
|
import getLength from '../internal/getLength';
|
|
import isArray from '../lang/isArray';
|
|
import isIterateeCall from '../internal/isIterateeCall';
|
|
import isLength from '../internal/isLength';
|
|
import isString from '../lang/isString';
|
|
import values from '../object/values';
|
|
|
|
/* Native method references for those with the same name as other `lodash` methods. */
|
|
var nativeMax = Math.max;
|
|
|
|
/**
|
|
* Checks if `value` is in `collection` using
|
|
* [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
|
|
* for equality comparisons. If `fromIndex` is negative, it is used as the offset
|
|
* from the end of `collection`.
|
|
*
|
|
* @static
|
|
* @memberOf _
|
|
* @alias contains, include
|
|
* @category Collection
|
|
* @param {Array|Object|string} collection The collection to search.
|
|
* @param {*} target The value to search for.
|
|
* @param {number} [fromIndex=0] The index to search from.
|
|
* @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
|
|
* @returns {boolean} Returns `true` if a matching element is found, else `false`.
|
|
* @example
|
|
*
|
|
* _.includes([1, 2, 3], 1);
|
|
* // => true
|
|
*
|
|
* _.includes([1, 2, 3], 1, 2);
|
|
* // => false
|
|
*
|
|
* _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
|
|
* // => true
|
|
*
|
|
* _.includes('pebbles', 'eb');
|
|
* // => true
|
|
*/
|
|
function includes(collection, target, fromIndex, guard) {
|
|
var length = collection ? getLength(collection) : 0;
|
|
if (!isLength(length)) {
|
|
collection = values(collection);
|
|
length = collection.length;
|
|
}
|
|
if (!length) {
|
|
return false;
|
|
}
|
|
if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
|
|
fromIndex = 0;
|
|
} else {
|
|
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
|
|
}
|
|
return (typeof collection == 'string' || !isArray(collection) && isString(collection))
|
|
? (fromIndex < length && collection.indexOf(target, fromIndex) > -1)
|
|
: (baseIndexOf(collection, target, fromIndex) > -1);
|
|
}
|
|
|
|
export default includes;
|