Skip to content

Commit 8513023

Browse files
author
Fabian Morón Zirfas
authored
Merge pull request #4 from tracker1/patch-1
Create from.js
2 parents 779e8a1 + 90a5131 commit 8513023

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

Array/from.js

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

0 commit comments

Comments
 (0)