-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
96 lines (73 loc) · 1.95 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
var Scuttlebutt = require("scuttlebutt")
, filter = Scuttlebutt.filter
, inherits = require("util").inherits
inherits(AppendOnly, Scuttlebutt)
var proto = AppendOnly.prototype
proto.push = push
proto.remove = remove
proto.applyUpdate = applyUpdate
proto.history = history
proto.toJSON = proto.createArray = createArray
module.exports = AppendOnly
function AppendOnly(options) {
if (! (this instanceof AppendOnly)) {
return new AppendOnly(options)
}
Scuttlebutt.call(this, options)
var store = this._store = []
this._hash = {}
this.on("_remove", function (update, update2) {
var index = store.indexOf(update)
if (index !== -1) {
store.splice(index, 1)
}
index = store.indexOf(update2)
if (index !== -1) {
store.splice(index, 1)
}
})
}
function push(item) {
this.localUpdate({ push: item })
}
function remove(id) {
this.localUpdate({ remove: id.__id ? id.__id : id })
}
function toId (update) {
var ts = update[1]
, source = update[2]
return source + ":" + ts
}
function applyUpdate(update) {
var value = update[0]
this._store.push(update)
if (value.push) {
var item = value.push
, id = toId(update)
Object.defineProperty(item, "__id", {
value: id
, configurable: true
})
this._hash[id] = update
this.emit("item", item)
} else if (value.remove) {
var id = value.remove
, _update = this._hash[id]
;delete this._hash[id]
this.emit("_remove", _update, update)
this.emit("remove", _update[0].push)
}
return true
}
function history(sources) {
return this._store.filter(function (update) {
return filter(update, sources)
})
}
function createArray() {
var hash = this._hash
return Object.keys(hash).map(findKey, hash)
}
function findKey(key) {
return this[key][0].push
}