Skip to content

Instantly share code, notes, and snippets.

@nberlette
Last active October 25, 2021 16:58
Show Gist options
  • Save nberlette/4529b54066574b693e605937f7625bd1 to your computer and use it in GitHub Desktop.
Save nberlette/4529b54066574b693e605937f7625bd1 to your computer and use it in GitHub Desktop.
localStorage with fallbacks and serialization
/**
* Setup custom localStorage instance.
* If we can't find localStorage, use a Map to use as a 'sessionStorage' clone.
* @returns {Storage}
*/
function setup () {
var storage = localStorage
? localStorage
: window.localStorage
? window.localStorage
: global.localStorage
? global.localStorage
: new Map();
if (!storage.prototype.get) {
storage.prototype.get = function (_key) {
let value = storage.getItem(_key) || storage[_key] || null
return JSON.parse(value) || null;
}
}
if (!storage.prototype.set) {
storage.prototype.set = function (_key, _value) {
let value = JSON.stringify(_value, null, 0)
storage.setItem(_key, value) || (storage[_key] = value)
return storage
}
}
if (!storage.prototype.remove) {
storage.protoype.remove = function (_key) {
storage.removeItem(_key) || storage.delete(_key);
return storage;
}
}
return storage;
}
/**
* Get a value from our Storage object, creating it first if necessary.
* @param {*} key the unique key whose value we want to fetch
* @param {*} fallback value to return in case of failure retrieving from localStorage
* @returns {unknown}
*/
function get (key = '', fallback = '') {
if (!storage) var storage = setup();
return storage.get(key) || fallback;
}
/**
* Set a value in our Storage object, creating it first if necessary.
* @param {string} key the unique key whose value we want to fetch
* @param {*} value the value to serialize and store
* @returns {unknown}
*/
function set (key = '', value) {
if (!storage) var storage = setup();
return storage.set(key, value)
}
/**
* Remove an entry from the storage object
* @param {*} key
* @returns
*/
function remove (key = '') {
if (!storage) var storage = setup();
return storage.remove(key)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment