2 // https://github.com/tc39/proposal-iterator-helpers
3 var $ = require('../internals/export');
4 var aFunction = require('../internals/a-function');
5 var anObject = require('../internals/an-object');
6 var getIteratorMethod = require('../internals/get-iterator-method');
7 var createIteratorProxy = require('../internals/iterator-create-proxy');
8 var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');
10 var IteratorProxy = createIteratorProxy(function (arg) {
11 var iterator = this.iterator;
12 var result, mapped, iteratorMethod, innerIterator;
15 if (innerIterator = this.innerIterator) {
16 result = anObject(this.innerNext.call(innerIterator));
17 if (!result.done) return result.value;
18 this.innerIterator = this.innerNext = null;
21 result = anObject(this.next.call(iterator, arg));
23 if (this.done = !!result.done) return;
25 mapped = callWithSafeIterationClosing(iterator, this.mapper, result.value);
26 iteratorMethod = getIteratorMethod(mapped);
28 if (iteratorMethod === undefined) {
29 throw TypeError('.flatMap callback should return an iterable object');
32 this.innerIterator = innerIterator = anObject(iteratorMethod.call(mapped));
33 this.innerNext = aFunction(innerIterator.next);
37 $({ target: 'Iterator', proto: true, real: true }, {
38 flatMap: function flatMap(mapper) {
39 return new IteratorProxy({
40 iterator: anObject(this),
41 mapper: aFunction(mapper),