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 |
|
---|
13 | var $Array = Array;
|
---|
14 |
|
---|
15 | // `Array.from` method implementation
|
---|
16 | // https://tc39.es/ecma262/#sec-array.from
|
---|
17 | module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
|
---|
18 | var O = toObject(arrayLike);
|
---|
19 | var IS_CONSTRUCTOR = isConstructor(this);
|
---|
20 | var argumentsLength = arguments.length;
|
---|
21 | var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
|
---|
22 | var mapping = mapfn !== undefined;
|
---|
23 | if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined);
|
---|
24 | var iteratorMethod = getIteratorMethod(O);
|
---|
25 | var index = 0;
|
---|
26 | var length, result, step, iterator, next, value;
|
---|
27 | // if the target is not iterable or it's an array with the default iterator - use a simple case
|
---|
28 | if (iteratorMethod && !(this === $Array && isArrayIteratorMethod(iteratorMethod))) {
|
---|
29 | result = IS_CONSTRUCTOR ? new this() : [];
|
---|
30 | iterator = getIterator(O, iteratorMethod);
|
---|
31 | next = iterator.next;
|
---|
32 | for (;!(step = call(next, iterator)).done; index++) {
|
---|
33 | value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
|
---|
34 | createProperty(result, index, value);
|
---|
35 | }
|
---|
36 | } else {
|
---|
37 | length = lengthOfArrayLike(O);
|
---|
38 | result = IS_CONSTRUCTOR ? new this(length) : $Array(length);
|
---|
39 | for (;length > index; index++) {
|
---|
40 | value = mapping ? mapfn(O[index], index) : O[index];
|
---|
41 | createProperty(result, index, value);
|
---|
42 | }
|
---|
43 | }
|
---|
44 | result.length = index;
|
---|
45 | return result;
|
---|
46 | };
|
---|