-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (46 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
// default to an in-memory cache
var cache = {};
// check for local storage support
if ('localStorage' in this) {
try {
var now = new Date().toString();
this.localStorage[now] = now;
if (this.localStorage[now] == now) {
delete this.localStorage[now];
cache = this.localStorage;
}
} catch (e) {}
}
module.exports = Store;
function Store(prefix) {
if (!(this instanceof Store)) {
return new Store(prefix);
}
this.prefix = prefix || 'publicclass/store/';
this.length = cache.length || Object.keys(cache).length || 0;
}
Store.prototype.set = function(key, data) {
var existed = (this.prefix + key) in cache;
var json = JSON.stringify(data);
cache[this.prefix + key] = json;
if (!existed) {
this.length += 1;
}
return data;
};
Store.prototype.get = function(key) {
var existed = (this.prefix + key) in cache;
if (existed) {
var json = cache[this.prefix + key];
return JSON.parse(json);
}
return undefined;
};
Store.prototype.del = function(key) {
var existed = (this.prefix + key) in cache;
if (existed) {
this.length -= 1;
}
delete cache[this.prefix + key];
return existed;
};