IteratorClose.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var $TypeError = GetIntrinsic('%TypeError%');
  4. var Call = require('./Call');
  5. var GetMethod = require('./GetMethod');
  6. var IsCallable = require('./IsCallable');
  7. var Type = require('./Type');
  8. // https://ecma-international.org/ecma-262/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)) {
  14. throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record');
  15. }
  16. var completionThunk = 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. };