GetIterator.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = require('es-errors/type');
  4. var $asyncIterator = GetIntrinsic('%Symbol.asyncIterator%', true);
  5. var inspect = require('object-inspect');
  6. var hasSymbols = require('has-symbols')();
  7. var AdvanceStringIndex = require('./AdvanceStringIndex');
  8. var CreateAsyncFromSyncIterator = require('./CreateAsyncFromSyncIterator');
  9. var GetIteratorFromMethod = require('./GetIteratorFromMethod');
  10. var GetMethod = require('./GetMethod');
  11. var IsArray = require('./IsArray');
  12. var getIteratorMethod = require('../helpers/getIteratorMethod');
  13. // https://262.ecma-international.org/14.0/#sec-getiterator
  14. module.exports = function GetIterator(obj, kind) {
  15. if (kind !== 'SYNC' && kind !== 'ASYNC') {
  16. throw new $TypeError("Assertion failed: `kind` must be one of 'sync' or 'async', got " + inspect(kind));
  17. }
  18. var method;
  19. if (kind === 'ASYNC') { // step 1
  20. if (hasSymbols && $asyncIterator) {
  21. method = GetMethod(obj, $asyncIterator); // step 1.a
  22. }
  23. }
  24. if (typeof method === 'undefined') { // step 1.b
  25. // var syncMethod = GetMethod(obj, $iterator); // step 1.b.i
  26. var syncMethod = getIteratorMethod(
  27. {
  28. AdvanceStringIndex: AdvanceStringIndex,
  29. GetMethod: GetMethod,
  30. IsArray: IsArray
  31. },
  32. obj
  33. );
  34. if (kind === 'ASYNC') {
  35. if (typeof syncMethod === 'undefined') {
  36. throw new $TypeError('iterator method is `undefined`'); // step 1.b.ii
  37. }
  38. var syncIteratorRecord = GetIteratorFromMethod(obj, syncMethod); // step 1.b.iii
  39. return CreateAsyncFromSyncIterator(syncIteratorRecord); // step 1.b.iv
  40. }
  41. method = syncMethod; // step 2, kind of
  42. }
  43. if (typeof method === 'undefined') {
  44. throw new $TypeError('iterator method is `undefined`'); // step 3
  45. }
  46. return GetIteratorFromMethod(obj, method); // step 4
  47. };