safeArrayFrom.mjs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. * Safer version of `Array.from` that return `null` if value isn't convertible to array.
  5. * Also protects against Array-like objects without items.
  6. *
  7. * @example
  8. *
  9. * safeArrayFrom([ 1, 2, 3 ]) // [1, 2, 3]
  10. * safeArrayFrom('ABC') // null
  11. * safeArrayFrom({ length: 1 }) // null
  12. * safeArrayFrom({ length: 1, 0: 'Alpha' }) // ['Alpha']
  13. * safeArrayFrom({ key: 'value' }) // null
  14. * safeArrayFrom(new Map()) // []
  15. *
  16. */
  17. export default function safeArrayFrom(collection) {
  18. var mapFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (item) {
  19. return item;
  20. };
  21. if (collection == null || _typeof(collection) !== 'object') {
  22. return null;
  23. }
  24. if (Array.isArray(collection)) {
  25. return collection.map(mapFn);
  26. } // Is Iterable?
  27. var iteratorMethod = collection[SYMBOL_ITERATOR];
  28. if (typeof iteratorMethod === 'function') {
  29. // $FlowFixMe[incompatible-use]
  30. var iterator = iteratorMethod.call(collection);
  31. var result = [];
  32. var step;
  33. for (var i = 0; !(step = iterator.next()).done; ++i) {
  34. result.push(mapFn(step.value, i));
  35. }
  36. return result;
  37. } // Is Array like?
  38. var length = collection.length;
  39. if (typeof length === 'number' && length >= 0 && length % 1 === 0) {
  40. var _result = [];
  41. for (var _i = 0; _i < length; ++_i) {
  42. if (!Object.prototype.hasOwnProperty.call(collection, _i)) {
  43. return null;
  44. }
  45. _result.push(mapFn(collection[String(_i)], _i));
  46. }
  47. return _result;
  48. }
  49. return null;
  50. }