getIteratorMethod.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. 'use strict';
  2. var hasSymbols = require('has-symbols')();
  3. var GetIntrinsic = require('get-intrinsic');
  4. var callBound = require('call-bind/callBound');
  5. var isString = require('is-string');
  6. var $iterator = GetIntrinsic('%Symbol.iterator%', true);
  7. var $stringSlice = callBound('String.prototype.slice');
  8. var $String = GetIntrinsic('%String%', true);
  9. module.exports = function getIteratorMethod(ES, iterable) {
  10. var usingIterator;
  11. if (hasSymbols) {
  12. usingIterator = ES.GetMethod(iterable, $iterator);
  13. } else if (ES.IsArray(iterable)) {
  14. usingIterator = function () {
  15. var i = -1;
  16. var arr = this; // eslint-disable-line no-invalid-this
  17. return {
  18. next: function () {
  19. i += 1;
  20. return {
  21. done: i >= arr.length,
  22. value: arr[i]
  23. };
  24. }
  25. };
  26. };
  27. } else if (isString(iterable)) {
  28. usingIterator = function () {
  29. var i = 0;
  30. return {
  31. next: function () {
  32. var nextIndex = ES.AdvanceStringIndex($String(iterable), i, true);
  33. var value = $stringSlice(iterable, i, nextIndex);
  34. i = nextIndex;
  35. return {
  36. done: nextIndex > iterable.length,
  37. value: value
  38. };
  39. }
  40. };
  41. };
  42. }
  43. return usingIterator;
  44. };