-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmap.js
50 lines (46 loc) · 1.29 KB
/
map.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
import transform from 'parallel-transform'
/**
* @typedef {(this: import('barnard59-core').Context, chunk: From) => Promise<To> | To} MapCallback
* @template From, To
*/
/**
* @typedef {{
* map: MapCallback<From, To>
* concurrency?: number
* ordered?: boolean
* objectMode?: boolean
* }|MapCallback<From, To>} MapOptions
* @template From, To
*/
/**
* Processes chunks with a transform function
*
* @this {import('barnard59-core').Context}
* @param {MapOptions<From, To>} options Transform function or complex options
* @return {import('stream').Transform}
* @template From, To
*/
export default function map(options) {
/**
* @type {MapCallback<*, *>}
*/
let func
let concurrency = 1
let ordered = true
let objectMode = true
if (typeof options === 'function') {
func = options
} else {
func = options.map
concurrency = options.concurrency || concurrency
ordered = typeof options.ordered === 'boolean' ? options.ordered : ordered
objectMode = typeof options.objectMode === 'boolean' ? options.objectMode : objectMode
}
return transform(concurrency, { ordered, objectMode }, (data, callback) => {
Promise.resolve().then(() => {
return func.call(this, data)
}).then(result => {
callback(null, result)
}).catch(callback)
})
}