-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
62 lines (58 loc) · 1.56 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var stream = require('stream');
exports.fromArray = function (array) {
var readable = new stream.Readable({ objectMode: true });
readable._read = function () {
for (var index = 0; index < array.length; index += 1) {
readable.push(array[index]);
}
readable.push(null);
};
return readable;
};
exports.map = function (iterator) {
var transform = new stream.Transform();
transform._readableState.objectMode = true;
transform._writableState.objectMode = true;
transform._transform = function (obj, encoding, next) {
if (!iterator) return next(null, obj);
if (iterator.length > 1) {
iterator(obj, next);
} else {
next(null, iterator(obj));
}
};
return transform;
};
exports.save = function (iterator, callback) {
var writable = new stream.Writable({ objectMode: true });
writable._write = function (obj, encoding, next) {
try {
if (iterator.length > 1) {
iterator(obj, next);
} else {
iterator(obj);
next();
}
} catch (err) {
next(err);
}
};
return writable.once('finish', function () {
callback && callback();
}).once('error', function (err) {
callback && callback(err);
});
};
exports.toArray = function (callback) {
var writable = new stream.Writable({ objectMode: true });
var array = [];
writable._write = function (obj, encoding, next) {
array.push(obj);
next();
};
return writable.once('finish', function () {
callback && callback(null, array);
}).once('error', function (err) {
callback && callback(err);
});
};