size.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. var baseKeys = require('./_baseKeys'),
  2. getTag = require('./_getTag'),
  3. isArrayLike = require('./isArrayLike'),
  4. isString = require('./isString'),
  5. stringSize = require('./_stringSize');
  6. /** `Object#toString` result references. */
  7. var mapTag = '[object Map]',
  8. setTag = '[object Set]';
  9. /**
  10. * Gets the size of `collection` by returning its length for array-like
  11. * values or the number of own enumerable string keyed properties for objects.
  12. *
  13. * @static
  14. * @memberOf _
  15. * @since 0.1.0
  16. * @category Collection
  17. * @param {Array|Object|string} collection The collection to inspect.
  18. * @returns {number} Returns the collection size.
  19. * @example
  20. *
  21. * _.size([1, 2, 3]);
  22. * // => 3
  23. *
  24. * _.size({ 'a': 1, 'b': 2 });
  25. * // => 2
  26. *
  27. * _.size('pebbles');
  28. * // => 7
  29. */
  30. function size(collection) {
  31. if (collection == null) {
  32. return 0;
  33. }
  34. if (isArrayLike(collection)) {
  35. return isString(collection) ? stringSize(collection) : collection.length;
  36. }
  37. var tag = getTag(collection);
  38. if (tag == mapTag || tag == setTag) {
  39. return collection.size;
  40. }
  41. return baseKeys(collection).length;
  42. }
  43. module.exports = size;