-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
iterator.js
61 lines (57 loc) · 1.2 KB
/
iterator.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
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Utility module to create and manipulate Iterators.
*
* @module iterator
*/
/**
* @template T,R
* @param {Iterator<T>} iterator
* @param {function(T):R} f
* @return {IterableIterator<R>}
*/
export const mapIterator = (iterator, f) => ({
[Symbol.iterator] () {
return this
},
// @ts-ignore
next () {
const r = iterator.next()
return { value: r.done ? undefined : f(r.value), done: r.done }
}
})
/**
* @template T
* @param {function():IteratorResult<T>} next
* @return {IterableIterator<T>}
*/
export const createIterator = next => ({
/**
* @return {IterableIterator<T>}
*/
[Symbol.iterator] () {
return this
},
// @ts-ignore
next
})
/**
* @template T
* @param {Iterator<T>} iterator
* @param {function(T):boolean} filter
*/
export const iteratorFilter = (iterator, filter) => createIterator(() => {
let res
do {
res = iterator.next()
} while (!res.done && !filter(res.value))
return res
})
/**
* @template T,M
* @param {Iterator<T>} iterator
* @param {function(T):M} fmap
*/
export const iteratorMap = (iterator, fmap) => createIterator(() => {
const { done, value } = iterator.next()
return { done, value: done ? undefined : fmap(value) }
})