polyfill.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. // The length property of the from method is 1.
  20. return function from(arrayLike/*, mapFn, thisArg */) {
  21. // 1. Let C be the this value.
  22. var C = this;
  23. // 2. Let items be ToObject(arrayLike).
  24. var items = Object(arrayLike);
  25. // 3. ReturnIfAbrupt(items).
  26. if (arrayLike == null) {
  27. throw new TypeError('Array.from requires an array-like object - not null or undefined');
  28. }
  29. // 4. If mapfn is undefined, then let mapping be false.
  30. var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
  31. var T;
  32. if (typeof mapFn !== 'undefined') {
  33. // 5. else
  34. // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
  35. if (!isCallable(mapFn)) {
  36. throw new TypeError('Array.from: when provided, the second argument must be a function');
  37. }
  38. // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
  39. if (arguments.length > 2) {
  40. T = arguments[2];
  41. }
  42. }
  43. // 10. Let lenValue be Get(items, "length").
  44. // 11. Let len be ToLength(lenValue).
  45. var len = toLength(items.length);
  46. // 13. If IsConstructor(C) is true, then
  47. // 13. a. Let A be the result of calling the [[Construct]] internal method
  48. // of C with an argument list containing the single item len.
  49. // 14. a. Else, Let A be ArrayCreate(len).
  50. var A = isCallable(C) ? Object(new C(len)) : new Array(len);
  51. // 16. Let k be 0.
  52. var k = 0;
  53. // 17. Repeat, while k < len… (also steps a - h)
  54. var kValue;
  55. while (k < len) {
  56. kValue = items[k];
  57. if (mapFn) {
  58. A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
  59. } else {
  60. A[k] = kValue;
  61. }
  62. k += 1;
  63. }
  64. // 18. Let putStatus be Put(A, "length", len, true).
  65. A.length = len;
  66. // 20. Return A.
  67. return A;
  68. };
  69. }());
  70. }