UNPKG

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