1 | 'use strict';
|
2 |
|
3 | var $ = require('../internals/export');
|
4 | var aFunction = require('../internals/a-function');
|
5 | var anObject = require('../internals/an-object');
|
6 | var isObject = require('../internals/is-object');
|
7 | var getIteratorMethod = require('../internals/get-iterator-method');
|
8 | var createIteratorProxy = require('../internals/create-iterator-proxy');
|
9 | var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');
|
10 |
|
11 | var IteratorProxy = createIteratorProxy(function (arg) {
|
12 | var iterator = this.iterator;
|
13 | var result, mapped, iteratorMethod, innerIterator;
|
14 |
|
15 | while (true) {
|
16 | if (innerIterator = this.innerIterator) {
|
17 | result = anObject(this.innerNext.call(innerIterator));
|
18 | if (!result.done) return result.value;
|
19 | this.innerIterator = this.innerNext = null;
|
20 | }
|
21 |
|
22 | result = anObject(this.next.call(iterator, arg));
|
23 |
|
24 | if (this.done = !!result.done) return;
|
25 |
|
26 | mapped = callWithSafeIterationClosing(iterator, this.mapper, result.value);
|
27 |
|
28 | if (isObject(mapped) && (iteratorMethod = getIteratorMethod(mapped)) !== undefined) {
|
29 | this.innerIterator = innerIterator = iteratorMethod.call(mapped);
|
30 | this.innerNext = aFunction(innerIterator.next);
|
31 | continue;
|
32 | } return mapped;
|
33 | }
|
34 | });
|
35 |
|
36 | $({ target: 'Iterator', proto: true, real: true }, {
|
37 | flatMap: function flatMap(mapper) {
|
38 | return new IteratorProxy({
|
39 | iterator: anObject(this),
|
40 | mapper: aFunction(mapper),
|
41 | innerIterator: null,
|
42 | innerNext: null
|
43 | });
|
44 | }
|
45 | });
|