Skip to content

Instantly share code, notes, and snippets.

@paceaux
Last active December 16, 2015 19:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paceaux/5483859 to your computer and use it in GitHub Desktop.
Save paceaux/5483859 to your computer and use it in GitHub Desktop.
A very basic JavaScript object that merges localStorage and sessionStorage, and allows you to store and retrieve either objects, arrays, or text strings as your values.
store = {
types: [localStorage,sessionStorage],
convertValue: function (v) {
return typeof v !== "object" ? v : JSON.stringify(v);
},
unconvertValue: function (v) {
if (v !== null) {
if ( v.indexOf("{") === 0 || v.indexOf("[") === 0 ) {
var v = JSON.parse(v);
return v;
} else {
return null;
}
}
},
set: function (type, k, v) {
var v = this.convertValue(v);
store.types[type].setItem(k,v);
},
get: function (type, k) {
var v = typeof k !== "number" ? store.types[type].getItem(k) : store.types[type].getItem(store.types[type].key(k));
return this.unconvertValue(v);
},
del: function (type, k) {
store.types[type].removeItem(k);
},
clr: function (type) {
store.types[type].clear();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment