/
index.js
40 lines (37 loc) · 1012 Bytes
/
index.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
// core
import { Readable as ReadableStream } from 'stream';
/** Readable stream from iterable
* @func
* @sig Iterable<a> → Stream<a>
* @example
* from([1, 2, 3]); // ReadableStream<1, 2, 3>
*/
const from = iterable => {
const stream = new ReadableStream();
for (const item of iterable) stream.push(item);
stream.push(null);
return stream;
};
/** Stream to string
* @func
* @sig Stream<String> → String
* @example
* await toString(from(['a', 'b', 'c'])); // 'abc'
*/
export const toString = async stream => {
return new Promise((resolve, reject) => {
const chunks = [];
/* eslint-disable indent */
stream.on('data', chunk => chunks.push(chunk.toString()))
.on('end', () => resolve(chunks.join('')))
.on('error', reject);
/* eslint-enable indent */
});
};
/** String to stream
* @func
* @sig String → Stream<String>
* @example
* fromString('hello'); // ReadableStream<'hello'>
*/
export const fromString = string => from([string]);