isCollection.js.flow 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // @flow strict
  2. import { SYMBOL_ITERATOR } from '../polyfills/symbols';
  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: mixed): boolean {
  25. if (obj == null || typeof obj !== 'object') {
  26. return false;
  27. }
  28. // Is Array like?
  29. const length = obj.length;
  30. if (typeof length === 'number' && length >= 0 && length % 1 === 0) {
  31. return true;
  32. }
  33. // Is Iterable?
  34. return typeof obj[SYMBOL_ITERATOR] === 'function';
  35. }