Skip to content

Instantly share code, notes, and snippets.

@tobiasroeder
Last active May 29, 2023 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobiasroeder/65ee295d7c8d4058b5fc52eddcf91298 to your computer and use it in GitHub Desktop.
Save tobiasroeder/65ee295d7c8d4058b5fc52eddcf91298 to your computer and use it in GitHub Desktop.
Store data as an single item in the local storage.
/**
* Store data as an single item in the local storage.
*
* @author Tobias Röder
* @version 1.0.0
*
* @property reck
* @property itemName
*
* @method init
* @method get
* @method add
* @method remove
* @method flush
* @method destroy
*/
const storage = {
/**
* @var Object
*/
reck: {},
/**
* @var String
*/
itemName: '',
/**
* Initialize the storage.
*
* @param {String} itemName The name (identifier) of the item in the local storage.
*
* @this storage
*/
init(itemName = 'heimkino') {
this.itemName = itemName;
if (localStorage.getItem(itemName) !== null) {
this.reck = JSON.parse(localStorage.getItem(itemName));
return this;
}
let initValue = {};
localStorage.setItem(itemName, JSON.stringify(initValue));
return this;
},
/**
* Save the reck in the local storage.
*
* @private
*/
save() {
localStorage.setItem(this.itemName, JSON.stringify(this.reck));
},
/**
* Get the value from an item of the reck.
*
* @param {String} key The key from the reck.
* @param {*} fallback Returns this fallback if the key does not exists.
*
* @returns {*} Returns the value on success, otherwise null.
*/
get(key, fallback = null) {
return this.reck[key] ?? fallback;
},
/**
* Add item to the reck.
*
* @param {String} key The key from the reck.
* @param {*} value The value.
*
* @this storage
*/
add(key, value) {
this.reck[key] = value;
this.save();
return this;
},
/**
* Remove an item of the reck.
*
* @param {String} key The key from the reck.
*
* @this storage
*/
remove(key) {
delete this.reck[key];
this.save();
return this;
},
/**
* Clear the local storage item.
*
* @this storage
*/
flush() {
this.reck = {};
this.save();
return this;
},
/**
* Remove the local storage item.
*
* @this storage
*/
destroy() {
localStorage.removeItem(this.itemName);
return this;
},
};
export default storage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment