collection/includes.jsjavascript
import { entries } from '../_internal/iteratee'
/**
* 判断集合是否包含指定值,比较遵循 SameValueZero 规则。
* @function includes
* @memberof module:collection
* @param {Array|Object|string} collection 要检查的集合或字符串
* @param {*} value 要查找的值
* @param {number} [fromIndex=0] 数组或字符串的起始索引
* @returns {boolean} 是否包含该值
* @throws {TypeError} 集合类型不支持时抛出
*/
function includes(collection, value, fromIndex = 0) {
if (typeof fromIndex !== 'number' || !Number.isInteger(fromIndex)) throw new TypeError('fromIndex must be an integer')
if (typeof collection === 'string') return collection.includes(String(value), Math.max(0, fromIndex))
if (Array.isArray(collection)) return collection.includes(value, fromIndex)
const sameValueZero = item => Object.is(item, value) || (Number.isNaN(item) && Number.isNaN(value))
return entries(collection).some(([, item]) => sameValueZero(item))
}
export default includes