size.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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;