IteratorClose.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var Call = require('es-abstract/2022/Call');
  5. var CompletionRecord = require('es-abstract/2022/CompletionRecord');
  6. var GetMethod = require('es-abstract/2022/GetMethod');
  7. var Type = require('es-abstract/2022/Type');
  8. var assertRecord = require('es-abstract/helpers/assertRecord');
  9. // https://262.ecma-international.org/14.0/#sec-iteratorclose
  10. module.exports = function IteratorClose(iteratorRecord, completion) {
  11. assertRecord(Type, 'Iterator Record', 'iteratorRecord', iteratorRecord);
  12. if (Type(iteratorRecord['[[Iterator]]']) !== 'Object') {
  13. throw new $TypeError('Assertion failed: iteratorRecord.[[Iterator]] must be an Object'); // step 1
  14. }
  15. if (!(completion instanceof CompletionRecord)) { // step 2
  16. throw new $TypeError('Assertion failed: completion is not a Completion Record instance');
  17. }
  18. var completionThunk = function () {
  19. var value = completion.value();
  20. if (completion.type() === 'throw') {
  21. throw value;
  22. }
  23. return value;
  24. };
  25. var iterator = iteratorRecord['[[Iterator]]']; // step 3
  26. var iteratorReturn;
  27. try {
  28. iteratorReturn = GetMethod(iterator, 'return'); // step 4
  29. } catch (e) {
  30. completionThunk(); // throws if `completion` is a throw completion // step 6
  31. completionThunk = null; // ensure it's not called twice.
  32. throw e; // step 7
  33. }
  34. if (typeof iteratorReturn === 'undefined') {
  35. return completionThunk(); // step 5.a - 5.b
  36. }
  37. var innerResult;
  38. try {
  39. innerResult = Call(iteratorReturn, iterator, []);
  40. } catch (e) {
  41. // if we hit here, then "e" is the innerResult completion that needs re-throwing
  42. completionThunk(); // throws if `completion` is a throw completion // step 6
  43. completionThunk = null; // ensure it's not called twice.
  44. // if not, then return the innerResult completion
  45. throw e; // step 7
  46. }
  47. var completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does
  48. completionThunk = null; // ensure it's not called twice.
  49. if (Type(innerResult) !== 'Object') {
  50. throw new $TypeError('iterator .return must return an object');
  51. }
  52. return completionRecord;
  53. };