-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (46 loc) · 1.09 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
var stream = require('stream')
, util = require('util')
module.exports = Format
util.inherits(Format, stream.Transform)
// Pass through until you come to the token, at
// which point you start reading from the first argument until it emits its
// end event.
function Format(context, match) {
stream.Transform.call(this)
this.stream = template_variable
this.match = match || equal
this.context = context
this._cache = {}
}
Format.prototype._transform = function(chunk, encoding, done) {
var flag = this.match(chunk, this.context)
if(!flag) {
this.push(chunk)
return done()
}
if(this._cache[flag].length) {
this.push(this._cache[flag].reduce(flatten, []))
return done()
}
this.pause()
this.stream.on('data', emit(this, flag))
this.stream.on('end', resume(this))
done()
}
function equal(lhs, rhs) {
return lhs === rhs
}
function flatten(lhs, rhs) {
return lhs.concat(rhs)
}
function emit(self, flag) {
return function(data) {
self.push(data)
self._cache[flag].push(data)
}
}
function resume(self) {
return function() {
self.resume()
}
}