forked from bevacqua/local-storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local-storage.js
49 lines (39 loc) · 861 Bytes
/
local-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
'use strict';
var stub = require('./stub');
var tracking = require('./tracking');
var ls = 'localStorage' in global && global.localStorage ? global.localStorage : stub;
function accessor (key, value) {
if (arguments.length === 1) {
return get(key);
}
return set(key, value);
}
function get (key) {
return JSON.parse(ls.getItem(key));
}
function set (key, value) {
try {
ls.setItem(key, JSON.stringify(value));
return true;
} catch (e) {
return false;
}
}
function remove (key) {
return ls.removeItem(key);
}
function clear () {
return ls.clear();
}
function backend (store) {
store && (ls = store);
return ls;
}
accessor.set = set;
accessor.get = get;
accessor.remove = remove;
accessor.clear = clear;
accessor.backend = backend;
accessor.on = tracking.on;
accessor.off = tracking.off;
module.exports = accessor;