-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdifference.js
79 lines (69 loc) · 1.88 KB
/
difference.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
var Cursor = require('./cursor')
var CursorStream = require('./stream')
var cmp = require('./cmp')
function Difference (blocks, cursors, reverse, limit) {
if(cursors.length !== 2) throw new Error('difference takes exactly two inputs')
// this.a = new Cursor(blocks, vectors[0], reverse)
// this.b = new Cursor(blocks, vectors[1], reverse)
this.a = cursors[0]
this.b = cursors[1]
this.value = 0
this.ended = false
this.reverse = !!reverse
CursorStream.call(this, limit)
this._blocks = blocks
}
Difference.prototype = new CursorStream()
Difference.prototype.ready = function () {
if(this.a.ready()) return this.b.ready() || this.b.isEnded()
this.value = this.a.value
return false
}
Difference.prototype.next = function () {
if(!this.ready()) throw new Error('next called when not ready')
var loop = true
this.value = 0
while(loop) {
loop = false
//bail if we need to update either cursor
if(
!this.a.ready() ||
(!this.b.ready() && !this.b.isEnded())
) return 0
if(this.b.isEnded()) {
this.a.next()
this.value = this.a.value
}
else if(cmp.lt(this.a.value, this.b.value, this.reverse)) {
this.value = this.a.value
this.a.next()
return this.value
}
else if(this.a.value == this.b.value) {
this.a.next(); this.b.next()
loop = true
}
else if(cmp.gt(this.a.value, this.b.value, this.reverse)) {
loop = true
this.b.next()
}
}
return this.value// = this.a.value
}
Difference.prototype.update = function (cb) {
const self = this
const cursors = this.cursors
if(!self.a.ready())
self.a.update(function () {
if(!self.b.ready()) self.b.update(next)
else next()
})
else self.b.update(next)
function next () {
self.ended = self.a.isEnded(); cb()
}
}
Difference.prototype.isEnded = function () {
return this.ended
}
module.exports = Difference