1 | const { Readable } = require('stream')
|
2 |
|
3 | const aliens = require('./aliens.json')
|
4 | const words = require('./words.json')
|
5 |
|
6 | const inputFromAliens = () => {
|
7 | const input = []
|
8 | for (let i = 0; i < 10; i++) {
|
9 | const alien = aliens[Math.floor(Math.random() * aliens.length)]
|
10 | input.push(`${alien}\n`)
|
11 | }
|
12 | return input
|
13 | }
|
14 |
|
15 | const inputFromWords = () => {
|
16 | const input = []
|
17 | const offset = Math.floor(words.length * Math.random())
|
18 | for (let i = 0; i < 10; i++) {
|
19 | const word = words[(offset + i) % words.length]
|
20 | input.push(`${word}\n`)
|
21 | }
|
22 | return input
|
23 | }
|
24 |
|
25 | const rndPort = () => Math.floor(Math.random() * 40000 + 10000)
|
26 |
|
27 | const writeStream = (stream, input, time) => {
|
28 | let count = 0
|
29 | const iv = setInterval(function () {
|
30 | stream.write(input[count].trim() + '\n')
|
31 |
|
32 | if (++count === input.length) {
|
33 | clearInterval(iv)
|
34 | stream.end()
|
35 | }
|
36 | }, time)
|
37 | }
|
38 |
|
39 | const readableStream = () => {
|
40 | const stream = new Readable({ objectMode: true })
|
41 | stream._read = function () {}
|
42 | return stream
|
43 | }
|
44 |
|
45 | module.exports = {
|
46 | inputFromAliens,
|
47 | inputFromWords,
|
48 | rndPort,
|
49 | writeStream,
|
50 | readableStream
|
51 | }
|