-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathFlatMappingIterator.js
49 lines (46 loc) · 1.14 KB
/
FlatMappingIterator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const genericReduce = require('./genericReduce')
const symbolIterator = require('./symbolIterator')
const arrayPush = require('./arrayPush')
/**
* @name FlatMappingIterator
*
* @synopsis
* ```coffeescript [specscript]
* FlatMappingIterator(
* iterator Iterator, flatMapper function,
* ) -> FlatMappingIterator { next, SymbolIterator }
* ```
*/
const FlatMappingIterator = function (iterator, flatMapper) {
let buffer = [],
bufferIndex = 0
return {
[symbolIterator]() {
return this
},
next() {
if (bufferIndex < buffer.length) {
const value = buffer[bufferIndex]
bufferIndex += 1
return { value, done: false }
}
const iteration = iterator.next()
if (iteration.done) {
return iteration
}
const monadAsArray = genericReduce(
flatMapper(iteration.value),
arrayPush,
[]) // this will always have at least one item
if (monadAsArray.length > 1) {
buffer = monadAsArray
bufferIndex = 1
}
return {
value: monadAsArray[0],
done: false,
}
},
}
}
module.exports = FlatMappingIterator