/
index.js
91 lines (79 loc) · 1.91 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var once = exports.once =
function (value) {
return function (abort, cb) {
if(abort) return cb(abort)
if(value != null) {
var _value = value; value = null
cb(null, _value)
} else
cb(true)
}
}
var depthFirst = exports.depthFirst =
function (start, createStream) {
var reads = [], ended
reads.unshift(once(start))
return function next (end, cb) {
if(!reads.length)
return cb(true)
if(ended)
return cb(ended)
reads[0](end, function (end, data) {
if(end) {
if(end !== true) {
ended = end
reads.shift()
while(reads.length)
reads.shift()(end, function () {})
return cb(end)
}
//if this stream has ended, go to the next queue
reads.shift()
return next(null, cb)
}
reads.unshift(createStream(data))
cb(end, data)
})
}
}
//width first is just like depth first,
//but push each new stream onto the end of the queue
var widthFirst = exports.widthFirst =
function (start, createStream) {
var reads = []
reads.push(once(start))
return function next (end, cb) {
if(!reads.length)
return cb(true)
reads[0](end, function (end, data) {
if(end) {
reads.shift()
return next(null, cb)
}
reads.push(createStream(data))
cb(end, data)
})
}
}
//this came out different to the first (strm)
//attempt at leafFirst, but it's still a valid
//topological sort.
var leafFirst = exports.leafFirst =
function (start, createStream) {
var reads = []
var output = []
reads.push(once(start))
return function next (end, cb) {
reads[0](end, function (end, data) {
if(end) {
reads.shift()
if(!output.length)
return cb(true)
return cb(null, output.shift())
}
reads.unshift(createStream(data))
output.unshift(data)
next(null, cb)
})
}
}