isCollection.mjs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  2. import { SYMBOL_ITERATOR } from "../polyfills/symbols.mjs";
  3. /**
  4. * Returns true if the provided object is an Object (i.e. not a string literal)
  5. * and is either Iterable or Array-like.
  6. *
  7. * This may be used in place of [Array.isArray()][isArray] to determine if an
  8. * object should be iterated-over. It always excludes string literals and
  9. * includes Arrays (regardless of if it is Iterable). It also includes other
  10. * Array-like objects such as NodeList, TypedArray, and Buffer.
  11. *
  12. * @example
  13. *
  14. * isCollection([ 1, 2, 3 ]) // true
  15. * isCollection('ABC') // false
  16. * isCollection({ length: 1, 0: 'Alpha' }) // true
  17. * isCollection({ key: 'value' }) // false
  18. * isCollection(new Map()) // true
  19. *
  20. * @param obj
  21. * An Object value which might implement the Iterable or Array-like protocols.
  22. * @return {boolean} true if Iterable or Array-like Object.
  23. */
  24. export default function isCollection(obj) {
  25. if (obj == null || _typeof(obj) !== 'object') {
  26. return false;
  27. } // Is Array like?
  28. var length = obj.length;
  29. if (typeof length === 'number' && length >= 0 && length % 1 === 0) {
  30. return true;
  31. } // Is Iterable?
  32. return typeof obj[SYMBOL_ITERATOR] === 'function';
  33. }