Skip to content

Instantly share code, notes, and snippets.

@Masquerade-Circus
Last active August 26, 2016 19:48
Show Gist options
  • Save Masquerade-Circus/658da13cde895a5f7e26e11d59bb1a71 to your computer and use it in GitHub Desktop.
Save Masquerade-Circus/658da13cde895a5f7e26e11d59bb1a71 to your computer and use it in GitHub Desktop.
sessionManager - sessionStorage/localStorage manager - Stores and retrive data from objects

#sessionManager // Stores and retrive data from objects like an orm style

window.session = sessionManager(sessionStorage,'reserva','-', reserva);

console.log(session()); // Get the main data object

session('hello-world','hola mundo') // sets the value of {hello:{world: 'hola mundo'}} its the same as reserva.hello.world = 'hola mundo'

console.log(session('hello-world')) // returns 'hola mundo' and its the same as reserva.hello.world
/**
* @param object - sessionStorage or localStorage object
* @param string - name of the data entry to store the session
* @param string - separator of the keys example '-'
* @param object - optional initial object if no session is loaded
* @return new sessionManager function.
*/
sessionManager = function (storage, name, separator, data ){
/**
* if no params return the main data object
* if only key return the value of that key
* if key and val set the value of that key to the val
* if key and val === null delete that key
*/
var f = function(key,val){
return key != undefined ? f.f(key,val) : f.data;
};
f.data = storage.getItem(name) ? JSON.parse(storage.getItem(name)) : data || {};
f.s = function(){
storage.setItem(name, JSON.stringify(f.data));
};
f.f = function(key,val){
var parsed = key.split(separator),
session = f.data,
last,next;
while (parsed.length > 1) {
next = parsed.shift();
if ( session[next] == undefined || typeof session[next] != 'object')
session[next] = {};
session = session[next];
}
last = parsed.shift();
if (val === undefined)
return session[last];
else if(val === null)
delete session[last];
else
session[last] = val;
f.s();
return f;
};
return f;
}
// Minified version
sessionManager=function(t,e,n,a){var i=function(t,e){return void 0!=t?i.f(t,e):i.data};return i.data=t.getItem(e)?JSON.parse(t.getItem(e)):a||{},i.s=function(){t.setItem(e,JSON.stringify(i.data))},i.f=function(t,e){for(var a,r,f=t.split(n),o=i.data;f.length>1;)r=f.shift(),(void 0==o[r]||"object"!=typeof o[r])&&(o[r]={}),o=o[r];return a=f.shift(),void 0===e?o[a]:(null===e?delete o[a]:o[a]=e,i.s(),i)},i}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment