-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
109 lines (101 loc) · 2.75 KB
/
main.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
(function(define) {
define([], function() {
var ls = window.localStorage;
var volatiles = {};
var Volatile = function(collectionName) {
this.collectionName = collectionName;
this.size = 0;
volatiles[collectionName] = this._index = {};
};
Volatile.prototype = {
get : function(key) {
return this._index[key];
},
set : function(key, data) {
if(!this.has(key))
this.size++;
this._index[key] = data;
},
remove : function(key) {
if(this.has(key))
this.size--;
delete this._index[key];
},
has: function() {
return !! this._index[key];
},
forEach : function(iterator) {
for (var key in this._index) {
iterator(this._index[key], key);
};
},
size : function() {
return this._index.length;
},
_destroy : function() {
delete volatiles[this.collectionName];
}
};
var Persistent = function(collectionName) {
this.collectionName = collectionName;
this._prefix = '__' + collectionName + '__';
this._countKey = '__' + collectionName + '-count__';
this._prefixRegExp = new RegExp('^' + this._prefix);
ls.getItem(this._countKey) || ls.setItem(this._countKey, 0);
};
Persistent.prototype = {
get : function(key) {
return JSON.parse(ls.getItem(this._prefix + key));
},
set : function(key, data) {
if (!ls.getItem(key))
ls.setItem(this._countKey, parseInt(ls.getItem(this._countKey)) + 1);
ls.setItem(this._prefix + key, JSON.stringify(data));
},
remove : function(key) {
if (ls.getItem(this._prefix + key))
ls.setItem(this._countKey, parseInt(ls.getItem(this._countKey)) - 1);
ls.removeItem(this._prefix + key);
},
has: function(key) {
return !!ls.getItem(this._prefix + key);
},
forEach : function(iterator) {
for (var i = 0; i < ls.length; i++) {
var keyCollection = ls.key(i), key;
if (this._prefixRegExp.test(keyCollection)) {
key = keyCollection.replace(this._prefixRegExp, '');
iterator(this.get(key), key);
}
}
},
size : function() {
return parseInt(ls.getItem(this._countKey));
},
_destroy : function() {
ls.removeItem(this._countKey);
for (var i = 0; i < ls.length; i++) {
var key = ls.key(i);
if (this._prefixRegExp.test(key)) {
ls.removeItem(key);
}
}
}
};
return {
Volatile : Volatile,
Persistent : Persistent,
get : function(collectionName) {
return new (!!ls ? Persistent : Volatile)(collectionName);
},
remove : function(collectionName) {
this.get(collectionName)._destroy();
},
setJsonUtil : function(JSONUtil) {
JSON = JSONUtil;
}
};
});
})( typeof define == "undefined" || !define.amd ? function(deps, factory) {
lightDb = factory();
} : define);