@vbarbarosh/node-helpers 3.40.0 → 3.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/stream_map.js +2 -2
- package/src/stream_map_parallel.js +65 -0
package/package.json
CHANGED
package/src/stream_map.js
CHANGED
|
@@ -7,9 +7,9 @@ function stream_map(fn)
|
|
|
7
7
|
{
|
|
8
8
|
return new stream.Transform({
|
|
9
9
|
objectMode: true,
|
|
10
|
-
transform: function (item, encoding, callback) {
|
|
10
|
+
transform: async function (item, encoding, callback) {
|
|
11
11
|
try {
|
|
12
|
-
this.push(fn(item));
|
|
12
|
+
this.push(await fn(item));
|
|
13
13
|
callback();
|
|
14
14
|
}
|
|
15
15
|
catch (error) {
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
const Promise = require('bluebird');
|
|
2
|
+
const stream = require('stream');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Transform each item by simple function in parallel.
|
|
6
|
+
*/
|
|
7
|
+
function stream_map_parallel({handler, concurrency})
|
|
8
|
+
{
|
|
9
|
+
let running = 0;
|
|
10
|
+
let callback_next = null;
|
|
11
|
+
let callback_flush = null;
|
|
12
|
+
const buf = [];
|
|
13
|
+
const buf_limit = 5*concurrency;
|
|
14
|
+
const out = new stream.Transform({
|
|
15
|
+
objectMode: true,
|
|
16
|
+
transform: async function (item, encoding, callback) {
|
|
17
|
+
try {
|
|
18
|
+
running++;
|
|
19
|
+
const promise = Promise.method(handler).call(null, item);
|
|
20
|
+
promise.then(ready).catch(fail);
|
|
21
|
+
buf.push(promise);
|
|
22
|
+
if (running < concurrency && buf.length < buf_limit) {
|
|
23
|
+
callback(); // Ready to consume the next item
|
|
24
|
+
}
|
|
25
|
+
else if (callback_next) {
|
|
26
|
+
throw new Error('Already pending');
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
callback_next = callback;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
callback(error);
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
flush: function (callback) {
|
|
37
|
+
if (buf.length === 0) {
|
|
38
|
+
callback();
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
callback_flush = callback;
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
return out;
|
|
46
|
+
function ready() {
|
|
47
|
+
running--;
|
|
48
|
+
while (buf.length && buf[0].isFulfilled()) {
|
|
49
|
+
out.push(buf.shift().value());
|
|
50
|
+
}
|
|
51
|
+
if (callback_next && buf.length < buf_limit) {
|
|
52
|
+
const tmp = callback_next;
|
|
53
|
+
callback_next = null;
|
|
54
|
+
tmp();
|
|
55
|
+
}
|
|
56
|
+
if (callback_flush && !buf.length) {
|
|
57
|
+
callback_flush();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function fail(error) {
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
module.exports = stream_map_parallel;
|