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 Type = require('./Type');
  14. // https://262.ecma-international.org/11.0/#sec-getiterator
  15. module.exports = function GetIterator(obj, hint, method) {
  16. var actualHint = hint;
  17. if (arguments.length < 2) {
  18. actualHint = 'sync';
  19. }
  20. if (actualHint !== 'sync' && actualHint !== 'async') {
  21. throw new $TypeError("Assertion failed: `hint` must be one of 'sync' or 'async', got " + inspect(hint));
  22. }
  23. var actualMethod = method;
  24. if (arguments.length < 3) {
  25. if (actualHint === 'async') {
  26. if (hasSymbols && $asyncIterator) {
  27. actualMethod = GetMethod(obj, $asyncIterator);
  28. }
  29. if (actualMethod === undefined) {
  30. throw new $SyntaxError("async from sync iterators aren't currently supported");
  31. }
  32. } else {
  33. actualMethod = getIteratorMethod(
  34. {
  35. AdvanceStringIndex: AdvanceStringIndex,
  36. GetMethod: GetMethod,
  37. IsArray: IsArray
  38. },
  39. obj
  40. );
  41. }
  42. }
  43. var iterator = Call(actualMethod, obj);
  44. if (Type(iterator) !== 'Object') {
  45. throw new $TypeError('iterator must return an object');
  46. }
  47. return iterator;
  48. // TODO: This should return an IteratorRecord
  49. /*
  50. var nextMethod = GetV(iterator, 'next');
  51. return {
  52. '[[Iterator]]': iterator,
  53. '[[NextMethod]]': nextMethod,
  54. '[[Done]]': false
  55. };
  56. */
  57. };