-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
59 lines (50 loc) · 1.62 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
var JSONStream = require('JSONStream');
var Stream = require('stream').Stream;
var es = require('event-stream');
var vm = require('vm');
var transfuse = module.exports = function (keyPath, fn, stringify, fnCtx) {
if (typeof keyPath === 'function') {
fn = keyPath;
keyPath = [ /./ ];
}
if (typeof fn === 'function' && fn.length === 1) {
return transfuse.sync(keyPath, fn, stringify, fnCtx);
}
else {
return transfuse.async(keyPath, fn, stringify, fnCtx);
}
};
transfuse.async = transform(function (fn, doc, map) {
fn.call(this, doc, map);
});
transfuse.sync = transform(function (fn, doc, map) {
map(fn.call(this, doc));
});
function transform (cb) {
return function (keyPath, fn, stringify, fnCtx) {
if (fnCtx === undefined) fnCtx = {}
if (fn === undefined) {
fn = keyPath;
keyPath = undefined;
}
if (!keyPath) keyPath = [ /./ ];
if (typeof fn !== 'function') {
var fn_ = vm.runInNewContext('(' + fn.toString() + ')', fnCtx);
return typeof fn_ === 'function'
? transfuse(keyPath, fn_, stringify)
: undefined
;
}
if (!stringify) stringify = JSONStream.stringify()
return es.connect(
JSONStream.parse(keyPath),
es.map(function (doc, map) {
var context = {
update : map.bind(null, null),
};
cb.call(context, fn, doc, map.bind(null, null));
}),
stringify
);
};
}