-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
117 lines (94 loc) · 2.25 KB
/
main.ts
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/usr/bin/env deno run --allow-env --allow-run
import { HTTPStatus } from '@oneday/http-status'
import stream from 'node:stream'
import { setTimeout as sleep } from 'node:timers/promises'
import process from 'node:process'
import { Buffer } from 'node:buffer'
import { pipeline } from 'node:stream/promises'
/**
* Adds x and y.
*
* # Examples
*
* ```ts
* import { assertEquals } from "jsr:@std/assert/equals";
*
* const sum = add(1, 2);
* assertEquals(sum, 3);
* ```
*/
export function add(x: number, y: number): number {
return x + y
}
console.log(add(1, 2))
console.log(HTTPStatus.OK)
console.info('\nPrepare\n---\n')
async function* generate() {
let index = 0
while (index < 4) {
await sleep(50)
index++
yield { name: 'hello' }
}
}
// Simple
// Test simple
// stream.Readable.from(generate()).on('data', (chunk) => console.log(chunk))
console.info('\nReadable\n---\n')
for await (const item of stream.Readable.from(generate())) {
console.log('readable:', item)
}
// Pipeline
console.info('\nPipeline\n---\n')
await pipeline(
generate(),
async function* (source) {
for await (const chunk of source) {
yield chunk.name.toString().toUpperCase()
}
},
async (source) => {
for await (const chunk of source) {
console.log('pipeline:', chunk)
}
},
)
// Transform
console.info('\nTransform\n---\n')
const upper = new stream.Transform({
transform: function (data, _enc, cb) {
this.push(Buffer.from(JSON.stringify({ name: data.name.toUpperCase() })))
cb()
},
objectMode: true,
})
stream.Readable.from(generate())
.pipe(upper)
.pipe(process.stdout)
// Pattern iterator async
console.info('\nTPattern iterator\n---\n')
function range(start: number, end: number, step = 1) {
let started = start
return {
[Symbol.iterator]() {
return this
},
async next() {
if (started < end) {
await sleep(10)
started = started + step
return { value: started, done: false }
}
return { done: true, value: end }
},
}
}
const countdown = range(0, 4, 2)
let result = await countdown.next()
while (!result.done) {
console.log('pattern iterator async:', result.value)
result = await countdown.next()
}
await sleep(1500)
console.log('')
console.info('bye')