-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
86 lines (62 loc) · 1.6 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
var stream = require('stream')
module.exports = Clock
function Clock(id, start) {
if(!(this instanceof Clock)) {
return Clock.apply(Object.create(Clock.prototype), arguments)
}
this.id = id
this.start = (start === undefined) ? 0 : start
this.clock = {}
this.clock[this.id] = this.start
return this
}
Clock.prototype.createReadStream = function() {
var self = this
var keys = Object.keys(self.clock).sort(randomize)
, out_stream
, opts
, i
i = 0
opts = {}
opts.highWaterMark = keys.length * 2
opts.objectMode = true
out_stream = new stream.Readable(opts)
out_stream._read = function() {
if(i >= keys.length) {
return out_stream.push(null)
}
var data
data = {}
data.id = keys[i]
data.version = self.get(keys[i])
out_stream.push(data)
++i
}
self.update(self.id)
return out_stream
}
function randomize(A, B) {
return Math.random() > 0.5 ? -1 : 1
}
Clock.prototype.get = function(source_id) {
if(this.clock.hasOwnProperty(source_id)) {
return this.clock[source_id]
}
return -Infinity
}
Clock.prototype.update = function(id, version) {
if(!this.clock.hasOwnProperty(id) && (id in this.clock)) {
throw new Error('Cannot override prototypal properties')
}
var current = id in this.clock ? this.clock[id] : this.start
if(id !== this.id && (undefined === version || null === version)) {
return false
}
if(id === this.id) {
this.clock[this.id]++
} else {
this.clock[id] = Math.max(current, version)
this.clock[this.id] = Math.max(version + 1, this.clock[this.id])
}
return this.clock[id]
}