local-storage
Version:
A simplified localStorage API that just works
53 lines (42 loc) • 932 B
JavaScript
;
var stub = require('./stub');
var parse = require('./parse');
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) {
const raw = ls.getItem(key);
const parsed = parse(raw);
return parsed;
}
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;