GetIterator.js 1.7 KB

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