es6.array.from.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. var ctx = require('./$.ctx')
  3. , $export = require('./$.export')
  4. , toObject = require('./$.to-object')
  5. , call = require('./$.iter-call')
  6. , isArrayIter = require('./$.is-array-iter')
  7. , toLength = require('./$.to-length')
  8. , getIterFn = require('./core.get-iterator-method');
  9. $export($export.S + $export.F * !require('./$.iter-detect')(function(iter){ Array.from(iter); }), 'Array', {
  10. // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
  11. from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
  12. var O = toObject(arrayLike)
  13. , C = typeof this == 'function' ? this : Array
  14. , $$ = arguments
  15. , $$len = $$.length
  16. , mapfn = $$len > 1 ? $$[1] : undefined
  17. , mapping = mapfn !== undefined
  18. , index = 0
  19. , iterFn = getIterFn(O)
  20. , length, result, step, iterator;
  21. if(mapping)mapfn = ctx(mapfn, $$len > 2 ? $$[2] : undefined, 2);
  22. // if object isn't iterable or it's array with default iterator - use simple case
  23. if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
  24. for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
  25. result[index] = mapping ? call(iterator, mapfn, [step.value, index], true) : step.value;
  26. }
  27. } else {
  28. length = toLength(O.length);
  29. for(result = new C(length); length > index; index++){
  30. result[index] = mapping ? mapfn(O[index], index) : O[index];
  31. }
  32. }
  33. result.length = index;
  34. return result;
  35. }
  36. });