Skip to content

Instantly share code, notes, and snippets.

@vermilion1
Last active April 23, 2016 14:08
Show Gist options
  • Save vermilion1/9293634 to your computer and use it in GitHub Desktop.
Save vermilion1/9293634 to your computer and use it in GitHub Desktop.
/*global define */
/*jshint expr:true */
define([], function () {
'use strict';
var hasLocalStorageSupport = (function () {
var str = 'storage-test-' + Math.random();
try {
localStorage.setItem(str, str);
localStorage.removeItem(str);
return true;
} catch (e) {
return false;
}
}());
var persist = hasLocalStorageSupport ? function (namespace, data) {
localStorage.setItem(namespace, JSON.stringify(data));
} : function () {};
return function (namespace) {
if (!namespace) {
throw new Error('Namespace is required');
}
var data = {};
try {
data = JSON.parse(localStorage.getItem(namespace)) || {};
}
catch (e) {}
return {
'clear': function () {
data = {};
persist(namespace, data);
},
'set': function (key, value) {
data[key] = value;
persist(namespace, data);
},
'get': function (path) {
return path.split('.').reduce(function (memo, val) {
return memo ? memo[val] : void 0;
}, data);
},
'export': function () {
return data;
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment