-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
89 lines (81 loc) · 2.4 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
module.exports = function combineLatest (streams) {
var isObj = !Array.isArray(streams) && typeof streams !== 'function'
if (!Array.isArray(streams) && !(isObj)) {
streams = [].slice.call(arguments)
}
var keys = Object.keys(streams)
if (isObj) {
streams = keys.map(function (k) {
return streams[k]
})
}
var l = streams.length
var buffer = []
var ended = []
var resolving = []
while (l--) {
buffer.push(null)
ended.push(false)
resolving.push(false)
}
var haveData = false
var err = null
var allEnded = false
var queue = []
var abort = null
var _emit
function emit (end, data) {
if (!_emit) return queue.push([end, data])
var cb = _emit
_emit = null
cb(end, data)
}
function source (_abort, emitNext) {
if (queue.length) return emitNext.apply(null, queue.shift())
abort = _abort || abort
_emit = emitNext
drain()
}
function drain () {
streams.forEach(function sink (s, i) {
if (ended[i] || resolving[i]) return
resolving[i] = true
s(abort || err, function onData (end, data) {
resolving[i] = false
if (err) return
if (end === true) {
ended[i] = true
allEnded = ended.every(function (e) {
return e === true
})
if (allEnded) emit(true)
return
}
err = end || err
if (err) {
ended[i] = true
// need to abort all other sources
drain()
return emit(err)
}
buffer[i] = data
if (!haveData) {
haveData = buffer.every(function (b) {
return b != null
})
}
if (haveData) {
if (!isObj) emit(null, [].concat(buffer))
else {
var val = {}
keys.forEach(function (k, i) {
val[k] = buffer[i]
})
emit(null, val)
}
}
})
})
}
return source
}