-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache.js
More file actions
57 lines (48 loc) · 1.22 KB
/
Copy pathcache.js
File metadata and controls
57 lines (48 loc) · 1.22 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
var Q = require('q');
var Cache = function(timeout) {
this.dictionary = {};
this.fns = [];
if (timeout) {
this.loop(timeout);
}
};
Cache.prototype.getValue = function(key) {
return this.dictionary[key];
};
Cache.prototype.setValue = function(key, value) {
this.dictionary[key] = value;
};
Cache.prototype.addPair = function(pair) {
this.dictionary[pair.key] = pair.value;
};
//takes key and function, replaces cache value of key with result of function on every iteration
//function should return promise
Cache.prototype.addFunction = function(key, fn) {
this.fns.push(wrap(key, fn));
};
Cache.prototype.loop = function(msTimeout) {
var cache = this;
cache.timeout = setTimeout(wrapper, msTimeout);
function wrapper() {
var promises = [];
for (var i = 0; i < cache.fns.length; i++) {
promises.push(cache.fns[i]().then(cache.addPair.bind(cache)));
}
Q.allSettled(promises).then(function() {
cache.loop(msTimeout);
});
}
};
Cache.prototype.stop = function() {
if (this.timeout) {
this.timeout.clearTimeout();
}
};
function wrap(key, fn) {
return function() {
return fn().then(function(value) {
return {key: key, value: value};
});
};
}
module.exports = Cache;