1 | 'use strict';
|
---|
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 iteratorClose = require('../internals/iterator-close');
|
---|
9 |
|
---|
10 | var IteratorProxy = createIteratorProxy(function (arg) {
|
---|
11 | var iterator = this.iterator;
|
---|
12 | var mapper = this.mapper;
|
---|
13 | var result, mapped, iteratorMethod, innerIterator;
|
---|
14 |
|
---|
15 | while (true) {
|
---|
16 | try {
|
---|
17 | if (innerIterator = this.innerIterator) {
|
---|
18 | result = anObject(this.innerNext.call(innerIterator));
|
---|
19 | if (!result.done) return result.value;
|
---|
20 | this.innerIterator = this.innerNext = null;
|
---|
21 | }
|
---|
22 |
|
---|
23 | result = anObject(this.next.call(iterator, arg));
|
---|
24 |
|
---|
25 | if (this.done = !!result.done) return;
|
---|
26 |
|
---|
27 | mapped = mapper(result.value);
|
---|
28 | iteratorMethod = getIteratorMethod(mapped);
|
---|
29 |
|
---|
30 | if (iteratorMethod === undefined) {
|
---|
31 | throw TypeError('.flatMap callback should return an iterable object');
|
---|
32 | }
|
---|
33 |
|
---|
34 | this.innerIterator = innerIterator = anObject(iteratorMethod.call(mapped));
|
---|
35 | this.innerNext = aFunction(innerIterator.next);
|
---|
36 | } catch (error) {
|
---|
37 | iteratorClose(iterator);
|
---|
38 | throw error;
|
---|
39 | }
|
---|
40 | }
|
---|
41 | });
|
---|
42 |
|
---|
43 | $({ target: 'Iterator', proto: true, real: true }, {
|
---|
44 | flatMap: function flatMap(mapper) {
|
---|
45 | return new IteratorProxy({
|
---|
46 | iterator: anObject(this),
|
---|
47 | mapper: aFunction(mapper),
|
---|
48 | innerIterator: null,
|
---|
49 | innerNext: null
|
---|
50 | });
|
---|
51 | }
|
---|
52 | });
|
---|