-
Notifications
You must be signed in to change notification settings - Fork 1
/
global-storage.js
116 lines (96 loc) · 2.9 KB
/
global-storage.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
115
116
(function (root, factory) {
if ( typeof define === 'function' && define.amd ) {
define(function() {
root.GlobalStorage = factory();
});
} else {
root.GlobalStorage = factory();
}
}(this, function() {
var data = {},
_get, _set,
extend,
isObject;
extend = function(base, object) {
var i;
for ( i in object ) {
if ( object.hasOwnProperty(i) ) {
base[i] = object[i];
}
}
return base;
}
isObject = function(object) {
return Object.prototype.toString.call(object) === '[object Object]';
}
_get = function(key, subdata) {
var result = null,
i;
if ( subdata === undefined ) {
subdata = data;
}
for ( i in subdata ) {
if ( subdata.hasOwnProperty(i) && key[0] == i ) {
if ( key.length <= 1 ) {
result = subdata[i];
break;
}
subdata = subdata[i];
if ( subdata === null || subdata === undefined ) {
result = null;
break;
}
if ( key.indexOf(i) !== -1 ) {
key.splice(key.indexOf(i), 1);
}
if ( key.length == 1 ) {
if ( isObject(subdata) ) {
result = !subdata.hasOwnProperty(key) || subdata[key] === undefined ? null : subdata[key];
} else {
result = null;
}
} else {
if ( isObject(subdata) ) {
result = _get(key, subdata);
} else {
result = null;
}
}
break;
}
}
return result;
};
_set = function(key, value) {
var subdata = {}, i, len;
key = key.reverse();
len = key.length;
for ( i = 0; i < len; i++ ) {
if ( i === 0 ) {
subdata[key[0]] = value;
} else {
subdata[key[i]] = extend({}, subdata);
delete subdata[key[i - 1]];
}
}
extend(data, subdata);
if ( value ) {
/*jshint evil:true */
eval('data' + '["' + key.reverse().join('"]["') + '"] = value;');
}
};
return {
get: function(key, defaultValue) {
var value = _get(key.split('.'));
return value !== null ? value : (defaultValue === undefined ? null : defaultValue);
},
set: function(key, value) {
_set(key.split('.'), value);
return this;
},
fromJSON: function(json) {
extend(data, JSON.parse(json) || {});
return this;
}
};
}));