UNPKG

1.56 kBJavaScriptView Raw
1'use strict';
2// https://github.com/tc39/proposal-iterator-helpers
3var $ = require('../internals/export');
4var aFunction = require('../internals/a-function');
5var anObject = require('../internals/an-object');
6var isObject = require('../internals/is-object');
7var getIteratorMethod = require('../internals/get-iterator-method');
8var createIteratorProxy = require('../internals/create-iterator-proxy');
9var callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');
10
11var 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});