Skip to content

Instantly share code, notes, and snippets.

@easrng
Last active April 2, 2020 21:24
Show Gist options
  • Save easrng/ca63e420862eb1c9db717cf2a5109fa8 to your computer and use it in GitHub Desktop.
Save easrng/ca63e420862eb1c9db717cf2a5109fa8 to your computer and use it in GitHub Desktop.
A way to implement custom localStorage alternatives.
function customStorage(backing){
var has = Object.prototype.hasOwnProperty
, storage = {};
/**
* Refresh the storage as other users might also be writing against it.
*
* @api private
*/
function update() {
if (!windowStorage.supported) return;
var data = backing.get()
, length = 0
, key;
storage = JSON.parse(data||"{}");
for (key in storage) {
if (has.call(storage, key)) length++;
}
windowStorage.length = length;
}
/**
* A DOM storage wrapper which uses the backing property to
* store values in the browser.
*
* @type {Object}
* @public
*/
var windowStorage = {
/**
* The total number items stored in the storage.
*
* @type {Number}
* @public
*/
length: 0,
/**
* Find an item in the storage.
*
* @param {String} key Name of the value we lookup.
* @returns {String|Null} Found item or null.
* @api public
*/
getItem: function getItem(key) {
if (has.call(storage, key)) return storage[key];
return null;
},
/**
* Add a new item in the storage.
*
* @param {String} key Name under which we store the value.
* @param {String} value Value for the key.
* @returns {Undefined}
* @api public
*/
setItem: function setItem(key, value) {
storage[key] = value;
backing.set(JSON.stringify(storage));
windowStorage.length++;
},
/**
* Remove a single item from the storage.
*
* @param {String} key Name of the value we need to remove.
* @returns {Undefined}
* @api pubilc
*/
removeItem: function removeItem(key) {
delete storage[key];
backing.set(JSON.stringify(storage));
windowStorage.length--;
},
/**
* Completely remove all items from the store.
*
* @returns {Undefined}
* @api pubilc
*/
clear: function clear() {
storage = {};
backing.set('');
windowStorage.length = 0;
},
/**
* Is this storage system supported in the current environment.
*
* @type {Boolean}
* @public
*/
supported: (function supported() {
return 'object' === typeof window
}())
};
//
// Make sure that we initialize the storage so it pre-fills the `.length`
//
update();
return windowStorage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment