array-from.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. var bind = require('../internals/function-bind-context');
  3. var call = require('../internals/function-call');
  4. var toObject = require('../internals/to-object');
  5. var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');
  6. var isArrayIteratorMethod = require('../internals/is-array-iterator-method');
  7. var isConstructor = require('../internals/is-constructor');
  8. var lengthOfArrayLike = require('../internals/length-of-array-like');
  9. var createProperty = require('../internals/create-property');
  10. var getIterator = require('../internals/get-iterator');
  11. var getIteratorMethod = require('../internals/get-iterator-method');
  12. var $Array = Array;
  13. // `Array.from` method implementation
  14. // https://tc39.es/ecma262/#sec-array.from
  15. module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
  16. var O = toObject(arrayLike);
  17. var IS_CONSTRUCTOR = isConstructor(this);
  18. var argumentsLength = arguments.length;
  19. var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
  20. var mapping = mapfn !== undefined;
  21. if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined);
  22. var iteratorMethod = getIteratorMethod(O);
  23. var index = 0;
  24. var length, result, step, iterator, next, value;
  25. // if the target is not iterable or it's an array with the default iterator - use a simple case
  26. if (iteratorMethod && !(this === $Array && isArrayIteratorMethod(iteratorMethod))) {
  27. iterator = getIterator(O, iteratorMethod);
  28. next = iterator.next;
  29. result = IS_CONSTRUCTOR ? new this() : [];
  30. for (;!(step = call(next, iterator)).done; index++) {
  31. value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
  32. createProperty(result, index, value);
  33. }
  34. } else {
  35. length = lengthOfArrayLike(O);
  36. result = IS_CONSTRUCTOR ? new this(length) : $Array(length);
  37. for (;length > index; index++) {
  38. value = mapping ? mapfn(O[index], index) : O[index];
  39. createProperty(result, index, value);
  40. }
  41. }
  42. result.length = index;
  43. return result;
  44. };