GetIterator.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. Type: Type
  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. };