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