es6.array.from.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. var ctx = require('./_ctx');
  3. var $export = require('./_export');
  4. var toObject = require('./_to-object');
  5. var call = require('./_iter-call');
  6. var isArrayIter = require('./_is-array-iter');
  7. var toLength = require('./_to-length');
  8. var createProperty = require('./_create-property');
  9. var getIterFn = require('./core.get-iterator-method');
  10. $export($export.S + $export.F * !require('./_iter-detect')(function (iter) { Array.from(iter); }), 'Array', {
  11. // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
  12. from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
  13. var O = toObject(arrayLike);
  14. var C = typeof this == 'function' ? this : Array;
  15. var aLen = arguments.length;
  16. var mapfn = aLen > 1 ? arguments[1] : undefined;
  17. var mapping = mapfn !== undefined;
  18. var index = 0;
  19. var iterFn = getIterFn(O);
  20. var length, result, step, iterator;
  21. if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
  22. // if object isn't iterable or it's array with default iterator - use simple case
  23. if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) {
  24. for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
  25. createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
  26. }
  27. } else {
  28. length = toLength(O.length);
  29. for (result = new C(length); length > index; index++) {
  30. createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
  31. }
  32. }
  33. result.length = index;
  34. return result;
  35. }
  36. });