GetIterator.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = require('es-errors/type');
  4. var $SyntaxError = require('es-errors/syntax');
  5. var $asyncIterator = GetIntrinsic('%Symbol.asyncIterator%', true);
  6. var inspect = require('object-inspect');
  7. var hasSymbols = require('has-symbols')();
  8. var getIteratorMethod = require('../helpers/getIteratorMethod');
  9. var AdvanceStringIndex = require('./AdvanceStringIndex');
  10. var Call = require('./Call');
  11. var GetMethod = require('./GetMethod');
  12. var IsArray = require('./IsArray');
  13. var isObject = require('../helpers/isObject');
  14. var ES = {
  15. AdvanceStringIndex: AdvanceStringIndex,
  16. GetMethod: GetMethod,
  17. IsArray: IsArray
  18. };
  19. // https://262.ecma-international.org/11.0/#sec-getiterator
  20. module.exports = function GetIterator(obj, hint, method) {
  21. var actualHint = hint;
  22. if (arguments.length < 2) {
  23. actualHint = 'sync';
  24. }
  25. if (actualHint !== 'sync' && actualHint !== 'async') {
  26. throw new $TypeError("Assertion failed: `hint` must be one of 'sync' or 'async', got " + inspect(hint));
  27. }
  28. var actualMethod = method;
  29. if (arguments.length < 3) {
  30. if (actualHint === 'async') {
  31. if (hasSymbols && $asyncIterator) {
  32. actualMethod = GetMethod(obj, $asyncIterator);
  33. }
  34. if (actualMethod === undefined) {
  35. throw new $SyntaxError("async from sync iterators aren't currently supported");
  36. }
  37. } else {
  38. actualMethod = getIteratorMethod(ES, obj);
  39. }
  40. }
  41. var iterator = Call(actualMethod, obj);
  42. if (!isObject(iterator)) {
  43. throw new $TypeError('iterator must return an object');
  44. }
  45. return iterator;
  46. // TODO: This should return an IteratorRecord
  47. /*
  48. var nextMethod = GetV(iterator, 'next');
  49. return {
  50. '[[Iterator]]': iterator,
  51. '[[NextMethod]]': nextMethod,
  52. '[[Done]]': false
  53. };
  54. */
  55. };