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