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