-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathmodel.js
86 lines (68 loc) · 1.73 KB
/
model.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 Scuttlebutt = require('./index')
var inherits = require('util').inherits
var each = require('iterate').each
var u = require('./util')
module.exports = Model
inherits(Model, Scuttlebutt)
function Model (opts) {
if(!(this instanceof Model)) return new Model(opts)
Scuttlebutt.call(this, opts)
this.store = {}
}
var m = Model.prototype
m.set = function (k, v) {
if(k==='__proto__') return u.protoIsIllegal(this)
this.localUpdate([k, v])
return this
}
m.get = function (k) {
if(k==='__proto__') return u.protoIsIllegal(this)
if(this.store[k])
return this.store[k][0][1]
}
m.keys = function () {
var a = []
for (var k in this.store)
a.push(k)
return a
}
m.forEach =
m.each = function (iter) {
for (var k in this.store)
iter(this.store[k][0][1], k, this.store)
return this
}
//return this history since sources.
//sources is a hash of { ID: TIMESTAMP }
m.applyUpdate = function (update) {
var key = update[0][0]
if('__proto__' === key) return u.protoIsIllegal(this)
//ignore if we already have a more recent value
if('undefined' !== typeof this.store[key]
&& this.store[key][1] > update[1])
return this.emit('_remove', update)
if(this.store[key]) this.emit('_remove', this.store[key])
this.store[key] = update
this.emit.apply(this, ['update'].concat(update))
this.emit('change', key, update[0][1])
this.emit('change:'+key, update[0][1])
return true
}
m.history = function (sources) {
var self = this
var h = []
each(this.store, function (e) {
if(u.filter(e, sources))
h.push(e)
})
return u.sort(h)
}
m.toJSON = function () {
var o = {}, notNull = false
for (var k in this.store) {
var v = this.get(k)
if(v != null)
o[k] = this.get(k)
}
return o
}