-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.js
98 lines (76 loc) · 1.93 KB
/
test.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const { PassThrough } = require('stream')
const tap = require('tap')
const pipe = require('./')
async function * produceIterator (n) {
for (let i = 0; i < n; i++) {
yield `produced "${i}"\n`
}
}
function produceStream (n) {
const stream = new PassThrough()
stream.setEncoding('utf8')
for (let i = 0; i < n; i++) {
stream.write(`produced "${i}"\n`)
}
stream.end()
return stream
}
async function * splitLines (iterator) {
let buffer = ''
for await (let item of iterator) {
buffer += item
let position = buffer.indexOf('\n')
while (position >= 0) {
yield buffer.slice(0, position + 1)
buffer = buffer.slice(position + 1)
position = buffer.indexOf('\n')
}
}
}
tap.test('iterator -> stream', t => {
t.plan(5)
const stream = new PassThrough()
stream.setEncoding('utf8')
let i = 0
stream.on('data', chunk => {
t.equal(chunk, `produced "${i++}"\n`)
})
pipe(produceIterator(5), stream)
})
tap.test('stream -> iterator', async t => {
t.plan(5)
let i = 0
for await (let chunk of pipe(produceStream(5), splitLines)) {
t.equal(chunk, `produced "${i++}"\n`)
}
})
tap.test('iterator -> iterator', async t => {
t.plan(5)
async function * upper (iterator) {
for await (let item of iterator) {
yield item.toString().toUpperCase()
}
}
let i = 0
for await (let chunk of pipe(produceIterator(5), upper)) {
t.equal(chunk, `PRODUCED "${i++}"\n`)
}
})
tap.test('stream -> iterator -> stream', t => {
t.plan(5)
const stream = new PassThrough()
stream.setEncoding('utf8')
let i = 0
stream.on('data', chunk => {
t.equal(chunk, `produced "${i++}"\n`)
})
pipe(produceStream(5), splitLines, stream)
})
tap.test('iterator -> stream -> iterator', async t => {
t.plan(5)
const stream = new PassThrough()
let i = 0
for await (let chunk of pipe(produceIterator(5), stream, splitLines)) {
t.equal(chunk, `produced "${i++}"\n`)
}
})