47 lines
2.0 KiB
JavaScript
47 lines
2.0 KiB
JavaScript
'use strict';
|
|
var bind = require('../internals/function-bind-context');
|
|
var call = require('../internals/function-call');
|
|
var toObject = require('../internals/to-object');
|
|
var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');
|
|
var isArrayIteratorMethod = require('../internals/is-array-iterator-method');
|
|
var isConstructor = require('../internals/is-constructor');
|
|
var lengthOfArrayLike = require('../internals/length-of-array-like');
|
|
var createProperty = require('../internals/create-property');
|
|
var getIterator = require('../internals/get-iterator');
|
|
var getIteratorMethod = require('../internals/get-iterator-method');
|
|
|
|
var $Array = Array;
|
|
|
|
// `Array.from` method implementation
|
|
// https://tc39.es/ecma262/#sec-array.from
|
|
module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {
|
|
var O = toObject(arrayLike);
|
|
var IS_CONSTRUCTOR = isConstructor(this);
|
|
var argumentsLength = arguments.length;
|
|
var mapfn = argumentsLength > 1 ? arguments[1] : undefined;
|
|
var mapping = mapfn !== undefined;
|
|
if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined);
|
|
var iteratorMethod = getIteratorMethod(O);
|
|
var index = 0;
|
|
var length, result, step, iterator, next, value;
|
|
// if the target is not iterable or it's an array with the default iterator - use a simple case
|
|
if (iteratorMethod && !(this === $Array && isArrayIteratorMethod(iteratorMethod))) {
|
|
result = IS_CONSTRUCTOR ? new this() : [];
|
|
iterator = getIterator(O, iteratorMethod);
|
|
next = iterator.next;
|
|
for (;!(step = call(next, iterator)).done; index++) {
|
|
value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;
|
|
createProperty(result, index, value);
|
|
}
|
|
} else {
|
|
length = lengthOfArrayLike(O);
|
|
result = IS_CONSTRUCTOR ? new this(length) : $Array(length);
|
|
for (;length > index; index++) {
|
|
value = mapping ? mapfn(O[index], index) : O[index];
|
|
createProperty(result, index, value);
|
|
}
|
|
}
|
|
result.length = index;
|
|
return result;
|
|
};
|