You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.7 KiB
41 lines
1.7 KiB
'use strict'; |
|
var bind = require('../internals/bind-context'); |
|
var toObject = require('../internals/to-object'); |
|
var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing'); |
|
var isArrayIteratorMethod = require('../internals/is-array-iterator-method'); |
|
var toLength = require('../internals/to-length'); |
|
var createProperty = require('../internals/create-property'); |
|
var getIteratorMethod = require('../internals/get-iterator-method'); |
|
|
|
// `Array.from` method implementation |
|
// https://tc39.github.io/ecma262/#sec-array.from |
|
module.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { |
|
var O = toObject(arrayLike); |
|
var C = typeof this == 'function' ? this : Array; |
|
var argumentsLength = arguments.length; |
|
var mapfn = argumentsLength > 1 ? arguments[1] : undefined; |
|
var mapping = mapfn !== undefined; |
|
var index = 0; |
|
var iteratorMethod = getIteratorMethod(O); |
|
var length, result, step, iterator; |
|
if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); |
|
// if the target is not iterable or it's an array with the default iterator - use a simple case |
|
if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) { |
|
iterator = iteratorMethod.call(O); |
|
result = new C(); |
|
for (;!(step = iterator.next()).done; index++) { |
|
createProperty(result, index, mapping |
|
? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) |
|
: step.value |
|
); |
|
} |
|
} else { |
|
length = toLength(O.length); |
|
result = new C(length); |
|
for (;length > index; index++) { |
|
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); |
|
} |
|
} |
|
result.length = index; |
|
return result; |
|
};
|
|
|