safeArrayFrom.js 2.0 KB

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