array-from.js 2.1 KB

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