1 | import { Readable, ReadableOptions } from 'stream'
|
2 | import { _passthroughMapper, AbortableAsyncMapper } from '@naturalcycles/js-lib'
|
3 | import { ReadableTyped } from '../stream.model'
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | export function readableFromArray<IN, OUT>(
|
12 | items: IN[],
|
13 | mapper: AbortableAsyncMapper<IN, OUT> = _passthroughMapper,
|
14 | opt?: ReadableOptions,
|
15 | ): ReadableTyped<OUT> {
|
16 | let i = -1
|
17 |
|
18 | return new Readable({
|
19 | objectMode: true,
|
20 | ...opt,
|
21 | async read() {
|
22 | i++
|
23 | if (i < items.length) {
|
24 | try {
|
25 | this.push(await mapper(items[i]!, i))
|
26 | } catch (err) {
|
27 | console.error(err)
|
28 | this.destroy(err as Error)
|
29 | }
|
30 | } else {
|
31 | this.push(null)
|
32 | }
|
33 | },
|
34 | })
|
35 | }
|