collection/size.jsjavascript
/**
* 返回集合的元素数量。
* @function size
* @memberof module:collection
* @param {Array|Object|string|Map|Set|null|undefined} collection 要统计的集合
* @returns {number} 元素数量;null 和 undefined 返回 0
* @throws {TypeError} 不支持的集合类型时抛出
*/
function size(collection) {
if (collection === null || collection === undefined) return 0
if (typeof collection === 'string' || Array.isArray(collection)) return collection.length
if (collection instanceof Map || collection instanceof Set) return collection.size
if (typeof collection === 'object') return Object.keys(collection).length
throw new TypeError('collection must be an array, string, object, Map, or Set')
}
export default size