UNPKG

2.73 kBJavaScriptView Raw
1/* tslint:disable */
2/* eslint-disable no-extend-native */
3
4// Production steps of ECMA-262, Edition 6, 22.1.2.1
5if (!Array.from) {
6 Array.from = (function () {
7 var toStr = Object.prototype.toString;
8 var isCallable = function (fn) {
9 return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
10 };
11 var toInteger = function (value) {
12 var number = Number(value);
13 if (isNaN(number)) { return 0; }
14 if (number === 0 || !isFinite(number)) { return number; }
15 return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
16 };
17 var maxSafeInteger = Math.pow(2, 53) - 1;
18 var toLength = function (value) {
19 var len = toInteger(value);
20 return Math.min(Math.max(len, 0), maxSafeInteger);
21 };
22
23 // The length property of the from method is 1.
24 return function from(arrayLike/*, mapFn, thisArg */) {
25 // 1. Let C be the this value.
26 var C = this;
27
28 // 2. Let items be ToObject(arrayLike).
29 var items = Object(arrayLike);
30
31 // 3. ReturnIfAbrupt(items).
32 if (arrayLike == null) {
33 throw new TypeError('Array.from requires an array-like object - not null or undefined');
34 }
35
36 // 4. If mapfn is undefined, then let mapping be false.
37 var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
38 var T;
39 if (typeof mapFn !== 'undefined') {
40 // 5. else
41 // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
42 if (!isCallable(mapFn)) {
43 throw new TypeError('Array.from: when provided, the second argument must be a function');
44 }
45
46 // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
47 if (arguments.length > 2) {
48 T = arguments[2];
49 }
50 }
51
52 // 10. Let lenValue be Get(items, "length").
53 // 11. Let len be ToLength(lenValue).
54 var len = toLength(items.length);
55
56 // 13. If IsConstructor(C) is true, then
57 // 13. a. Let A be the result of calling the [[Construct]] internal method
58 // of C with an argument list containing the single item len.
59 // 14. a. Else, Let A be ArrayCreate(len).
60 var A = isCallable(C) ? Object(new C(len)) : new Array(len);
61
62 // 16. Let k be 0.
63 var k = 0;
64 // 17. Repeat, while k < len… (also steps a - h)
65 var kValue;
66 while (k < len) {
67 kValue = items[k];
68 if (mapFn) {
69 A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
70 } else {
71 A[k] = kValue;
72 }
73 k += 1;
74 }
75 // 18. Let putStatus be Put(A, "length", len, true).
76 A.length = len;
77 // 20. Return A.
78 return A;
79 };
80 }());
81}
\No newline at end of file