Last active
April 2, 2020 21:24
-
-
Save easrng/ca63e420862eb1c9db717cf2a5109fa8 to your computer and use it in GitHub Desktop.
A way to implement custom localStorage alternatives.
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
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