IterableToArrayLike.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. var callBound = require('call-bind/callBound');
  3. var $arrayPush = callBound('Array.prototype.push');
  4. var getIteratorMethod = require('../helpers/getIteratorMethod');
  5. var AdvanceStringIndex = require('./AdvanceStringIndex');
  6. var GetIterator = require('./GetIterator');
  7. var GetMethod = require('./GetMethod');
  8. var IsArray = require('./IsArray');
  9. var IteratorStep = require('./IteratorStep');
  10. var IteratorValue = require('./IteratorValue');
  11. var ToObject = require('./ToObject');
  12. var Type = require('./Type');
  13. var ES = {
  14. AdvanceStringIndex: AdvanceStringIndex,
  15. GetMethod: GetMethod,
  16. IsArray: IsArray,
  17. Type: Type
  18. };
  19. // https://262.ecma-international.org/7.0/#sec-iterabletoarraylike
  20. /**
  21. * 1. Let usingIterator be ? GetMethod(items, @@iterator).
  22. * 2. If usingIterator is not undefined, then
  23. * 1. Let iterator be ? GetIterator(items, usingIterator).
  24. * 2. Let values be a new empty List.
  25. * 3. Let next be true.
  26. * 4. Repeat, while next is not false
  27. * 1. Let next be ? IteratorStep(iterator).
  28. * 2. If next is not false, then
  29. * 1. Let nextValue be ? IteratorValue(next).
  30. * 2. Append nextValue to the end of the List values.
  31. * 5. Return CreateArrayFromList(values).
  32. * 3. NOTE: items is not an Iterable so assume it is already an array-like object.
  33. * 4. Return ! ToObject(items).
  34. */
  35. module.exports = function IterableToArrayLike(items) {
  36. var usingIterator = getIteratorMethod(ES, items);
  37. if (typeof usingIterator !== 'undefined') {
  38. var iterator = GetIterator(items, usingIterator);
  39. var values = [];
  40. var next = true;
  41. while (next) {
  42. next = IteratorStep(iterator);
  43. if (next) {
  44. var nextValue = IteratorValue(next);
  45. $arrayPush(values, nextValue);
  46. }
  47. }
  48. return values;
  49. }
  50. return ToObject(items);
  51. };