-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStore.js
114 lines (86 loc) · 2.59 KB
/
Store.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
110
111
112
113
114
(function(win) {
'use strict';
function Store() {}
Store.prototype.put = put;
Store.prototype.get = get;
Store.prototype.remove = remove;
if(win.localStorage) {
Store.prototype.save = save;
Store.prototype.load = load;
Store.prototype.clear = clear;
}
win.Store = Store;
function put(keys, value) {
if(value === undefined || keys === undefined) {
_state.call(this, value || keys);
} else if(_isArray(keys) && _isArray(value)) {
if(typeof keys === 'string') {
keys = _flattenKeys(keys);
}
for(var i = 0; i < value.length; i++) {
this.put(keys[i], value[i]);
}
} else {
var keys = _flattenKeys(keys);
var parent = _find.call(this, keys, true);
var targetProperty = keys.slice(-1);
parent[targetProperty] = value;
return parent[targetProperty];
}
return this;
}
function get(keys) {
if(keys === undefined) { return this; }
var keys = _flattenKeys(keys);
var parentObj = _find.call(this, keys);
if(parentObj === undefined) { return; }
return parentObj[keys.slice(-1)];
}
function remove(keys) {
var keys = _flattenKeys(keys);
delete _find.call(this, keys)[keys.slice(-1)];
return this;
}
function save(saveKey) {
win.localStorage.setItem(saveKey, JSON.stringify(this));
}
function load(saveKey) {
var cachedData = JSON.parse(win.localStorage.getItem(saveKey));
if(cachedData) {
_state.call(this, cachedData);
return this;
}
return undefined;
}
function clear(saveKey) {
win.localStorage.removeItem(saveKey);
}
function _flattenKeys(keys) {
if(typeof keys === 'string') {
return keys.split('.');
} else if(keys.length) {
return keys;
} else {
return [keys];
}
}
function _find(array, put) {
var value = this;
for(var i = 0; i < array.length; i++) {
if(i+1 === array.length) { break; }
if(put && value[array[i]] === undefined) {
value[array[i]] = {};
}
value = value[array[i]];
}
return value;
}
function _state(obj) {
for(var prop in obj) {
this[prop] = obj[prop];
}
}
function _isArray(value) {
return (value.length && typeof value === 'object');
}
})(window);