-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtee.ts
More file actions
35 lines (27 loc) · 856 Bytes
/
tee.ts
File metadata and controls
35 lines (27 loc) · 856 Bytes
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
// Tees an iterable into two iterables while keeping memory costs low.
// Functional style.
export function tee<T>(iterable: Iterable<T>): [Generator<T>, Generator<T>] {
const iterator = iterable[Symbol.iterator]()
let isDone = false
const aQueue: T[] = []
const bQueue: T[] = []
function* teePart(myQueue: T[], otherQueue: T[]) {
while (true) {
if (myQueue.length != 0) {
yield myQueue.shift()!
continue
}
if (isDone) {
return
}
const result = iterator.next()
if (result.done) {
isDone = true
return
}
otherQueue.push(result.value)
yield result.value
}
}
return [teePart(aQueue, bQueue), teePart(bQueue, aQueue)]
}