IteratorClose.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var Call = require('./Call');
  4. var CompletionRecord = require('./CompletionRecord');
  5. var GetMethod = require('./GetMethod');
  6. var IsCallable = require('./IsCallable');
  7. var Type = require('./Type');
  8. // https://262.ecma-international.org/6.0/#sec-iteratorclose
  9. module.exports = function IteratorClose(iterator, completion) {
  10. if (Type(iterator) !== 'Object') {
  11. throw new $TypeError('Assertion failed: Type(iterator) is not Object');
  12. }
  13. if (!IsCallable(completion) && !(completion instanceof CompletionRecord)) {
  14. throw new $TypeError('Assertion failed: completion is not a thunk representing a Completion Record, nor a Completion Record instance');
  15. }
  16. var completionThunk = completion instanceof CompletionRecord ? function () { return completion['?'](); } : completion;
  17. var iteratorReturn = GetMethod(iterator, 'return');
  18. if (typeof iteratorReturn === 'undefined') {
  19. return completionThunk();
  20. }
  21. var completionRecord;
  22. try {
  23. var innerResult = Call(iteratorReturn, iterator, []);
  24. } catch (e) {
  25. // if we hit here, then "e" is the innerResult completion that needs re-throwing
  26. // if the completion is of type "throw", this will throw.
  27. completionThunk();
  28. completionThunk = null; // ensure it's not called twice.
  29. // if not, then return the innerResult completion
  30. throw e;
  31. }
  32. completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does
  33. completionThunk = null; // ensure it's not called twice.
  34. if (Type(innerResult) !== 'Object') {
  35. throw new $TypeError('iterator .return must return an object');
  36. }
  37. return completionRecord;
  38. };