-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (56 loc) · 1.72 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { isString } from '../ohjs-is/index.js';
/**
* A wrapper for increased usability of `window.localStorage`.
*
* All values are automatically JSON encoded.
*
* Namespacing is used when clearing local storage
* in an effort to only clear values for one instance.
*
* Versioning is to easily make existing local storage values obsolete.
*
* @param {string} namespace
* @param {string} version
*/
export default function(namespace, version) {
if (!namespace || !isString(namespace)) {
throw '`namespace` must be a non-empty string';
}
if (!version || !isString(version)) {
throw '`version` must be a non-empty string';
}
namespace = '::' + namespace;
version = '::' + version;
function getKey(key) {
return key + version + namespace;
}
return {
getItem(key) {
let value = window.localStorage.getItem(getKey(key));
if (!value) {
return value;
}
return JSON.parse(value);
},
setItem(key, value) {
window.localStorage.setItem(getKey(key),
JSON.stringify(value));
},
removeItem(key) {
window.localStorage.removeItem(getKey(key));
},
clear() {
let itemsToRemove = [];
const regexp = new RegExp(namespace + '$');
for (let i = 0; i < window.localStorage.length; i++) {
const key = window.localStorage.key(i);
if (key.match(regexp)) {
itemsToRemove.push(key);
}
}
itemsToRemove.forEach((itemToRemove) => {
window.localStorage.removeItem(itemToRemove);
});
},
};
}