Last active
April 23, 2016 14:08
-
-
Save vermilion1/9293634 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*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