Last active
December 16, 2015 19:19
-
-
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.
This file contains hidden or 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
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