-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
128 lines (101 loc) · 2.72 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
var Scuttlebutt = require("scuttlebutt")
, updateIsRecent = Scuttlebutt.updateIsRecent
, EventEmitter = require("events").EventEmitter
, iterators = require("iterators")
, reduce = iterators.reduceSync
, forEach = iterators.forEachSync
module.exports = Delta
/*
Protocol is [key, value, source, timestamp]
*/
function Delta(id, silent) {
var scutt = Scuttlebutt(id)
, delta = new EventEmitter()
, updates = {}
, state = { id: scutt.id }
, log = silent ? noop : error
id = delta.id = scutt.id
scutt.applyUpdate = applyUpdate
// history is a global variable -.-
scutt.history = $history
delta.validate = validate
delta.set = set
delta.get = get
delta.has = has
// stupid tokens
delta.delete = $delete
delta.toJSON = toJSON
delta.createStream = scutt.createStream.bind(scutt)
return delta
function applyUpdate(update) {
var key = update[0]
, value = update[1]
, recentUpdate = updates[key]
// If the most recent update for that key is newer then the incoming
// update. Then ignore it
if (recentUpdate && recentUpdate[2] > update[2]) {
return
}
updates[key] = update
if (value === undefined) {
delete state[key]
} else {
state[key] = value
}
delta.emit("change", key, value)
delta.emit("change:" + key, value)
return true
}
function $history(sources) {
return reduce(updates, isRecent, sources, []).sort(byTimestamp)
}
function validate(changes) {
try {
delta.emit("validate", changes)
return true
} catch (e) {
log("[DELTA-STREAM]: validation", e.message, e)
return false
}
}
function set(key, value) {
if (key === "id" && value !== id) {
console.log("invalid", key, value)
throw Error("id cannot be changed")
}
if (typeof key === "string") {
scutt.localUpdate(key, value)
} else {
forEach(key, setKeyValue)
}
}
function setKeyValue(value, key) {
set(key, value)
}
function get(key) {
return state[key]
}
function has(key) {
return key in state
}
function $delete(key) {
set(key, undefined)
}
function toJSON() {
return state
}
}
function isRecent(acc, update) {
var sources = this
if (updateIsRecent(update, sources)) {
acc.push(update)
}
return acc
}
function byTimestamp(a, b) {
return a[2] - b[2]
}
function noop() {}
function error() {
console.error.apply(console, arguments)
}