isIterableObject.mjs 819 B

12345678910111213141516171819202122232425
  1. /**
  2. * Returns true if the provided object is an Object (i.e. not a string literal)
  3. * and implements the Iterator protocol.
  4. *
  5. * This may be used in place of [Array.isArray()][isArray] to determine if
  6. * an object should be iterated-over e.g. Array, Map, Set, Int8Array,
  7. * TypedArray, etc. but excludes string literals.
  8. *
  9. * @example
  10. * ```ts
  11. * isIterableObject([ 1, 2, 3 ]) // true
  12. * isIterableObject(new Map()) // true
  13. * isIterableObject('ABC') // false
  14. * isIterableObject({ key: 'value' }) // false
  15. * isIterableObject({ length: 1, 0: 'Alpha' }) // false
  16. * ```
  17. */
  18. export function isIterableObject(maybeIterable) {
  19. return (
  20. typeof maybeIterable === 'object' &&
  21. typeof (maybeIterable === null || maybeIterable === void 0
  22. ? void 0
  23. : maybeIterable[Symbol.iterator]) === 'function'
  24. );
  25. }