-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (59 loc) · 1.14 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
function mkCache(createFn) {
var data = {};
return {
get: function(id) {
if (id == null) return id;
const value = data[id];
if (value) return value;
const el = createFn(id);
data[id] = el;
return el;
},
getAll: function () {
return data;
},
check: function(id) {
return data[id] !== undefined;
},
clear: function() {
data = {};
},
remove: function(id) {
delete data[id];
}
}
}
function mkCachePromise(createFn) {
var data = {};
return {
get: function(id) {
if (id == null) return Promise.resolve(id); // allow null and undefined for id here
const val = data[id];
if (val) return val;
var newVal = createFn(id);
if (newVal != null && newVal.then) { // check for a promise result
data[id] = newVal;
return newVal;
}
else {
newVal = Promise.resolve(newVal);
data[id] = newVal;
return newVal;
}
},
getAll: function () {
return data;
},
check: function(id) {
return data[id] !== undefined;
},
clear: function() {
data = {};
},
remove: function(id) {
delete data[id];
}
}
}
exports.Sync = mkCache;
exports.Async = mkCachePromise;