forked from pajlada/plugAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbufferObject.js
More file actions
68 lines (60 loc) · 1.85 KB
/
Copy pathbufferObject.js
File metadata and controls
68 lines (60 loc) · 1.85 KB
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
var util = require('util');
function BufferObject(data, getUpdate, maxAge) {
if (typeof getUpdate != 'function') {
throw new Error('BufferObject requires a update function');
}
maxAge = maxAge || 6e4;
//noinspection JSUnusedGlobalSymbols
return {
lastUpdate: data ? Date.now() : 0,
data: data || null,
set: function(data) {
this.data = data;
this.lastUpdate = Date.now();
},
get: function(callback) {
if (this.data != null) {
if (maxAge < 0 || this.lastUpdate >= Date.now() - maxAge) {
if (typeof callback == 'function')
callback(this.data);
return;
}
}
var that = this;
getUpdate(function(err, data) {
if (err) {
that.get();
return;
}
that.set(data);
if (typeof callback == 'function')
callback(data);
});
},
push: function(data) {
// Be sure the data is loaded
this.get();
if (util.isArray(this.data)) {
this.data.push(data);
}
},
remove: function(data) {
this.get();
for (var i in this.data) {
if (!this.data.hasOwnProperty(i)) continue;
if (this.data[i] == data) {
this.data.splice(i, 1);
return;
}
}
},
removeAt: function(index) {
// Be sure the data is loaded
this.get();
if (util.isArray(this.data) && index < this.data.length) {
this.data.splice(index, 1);
}
}
};
}
module.exports = BufferObject;