-
Notifications
You must be signed in to change notification settings - Fork 6
/
LocalStorageHandler.js
106 lines (92 loc) · 2.73 KB
/
LocalStorageHandler.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
/**
* A class for easing HTML5 LocalStorage handling. Licensed under CC BY 3.0.
* https://github.com/joaocunha/javascript-localstorage-handler/
*
* @author João Cunha - [email protected]
* @class LocalStorageHandler
* @constructor
*/
;(function(win) {
'use strict';
var LocalStorageHandler = function() {
/**
* @property _ls
* @private
* @type Object
*/
var _ls = win.localStorage;
/**
* @property length
* @type Number
*/
this.length = _ls.length;
/**
* @method get
* @param key {String} Item key
* @return {String|Object|Null}
*/
this.get = function(key) {
try {
return JSON.parse(_ls.getItem(key));
} catch(e) {
return _ls.getItem(key);
}
};
/**
* @method set
* @param key {String} Item key
* @param val {String|Object} Item value
* @return {String|Object} The value of the item just set
*/
this.set = function(key, val) {
_ls.setItem(key,JSON.stringify(val));
return this.get(key);
};
/**
* @method key
* @param index {Number} Item index
* @return {String|Null} The item key if found, null if not
*/
this.key = function(index) {
if (typeof index === 'number') {
return _ls.key(index);
}
};
/**
* @method data
* @return {Array|Null} An array containing all items in localStorage through key{string}-value{String|Object} pairs
*/
this.data = function() {
var i = 0;
var data = [];
while (_ls.key(i)) {
data[i] = [_ls.key(i), this.get(_ls.key(i))];
i++;
}
return data.length ? data : null;
};
/**
* @method remove
* @param keyOrIndex {String|Number} Item key or index (which will be converted to key anyway)
* @return {Boolean} True if the key was found before deletion, false if not
*/
this.remove = function(keyOrIndex) {
var result = false;
var key = (typeof keyOrIndex === 'number') ? this.key(keyOrIndex) : keyOrIndex;
if (key in _ls) {
result = true;
_ls.removeItem(key);
}
return result;
};
/**
* @method clear
* @return {Number} The total of items removed
*/
this.clear = function() {
var len = _ls.length;
_ls.clear();
return len;
};
}
})(window);