GetIterator.js 1.7 KB

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