Created
October 10, 2018 23:19
-
-
Save stockenberg/6bf2079bba837fa2139c4a1ecaa91ea1 to your computer and use it in GitHub Desktop.
LocalStorage
This file contains 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
class Storage { | |
/** | |
* Add to LocalStorage | |
* @param {*} key | |
* @param {*} value | |
*/ | |
static add(key, value) { | |
let storage = this.get(key); | |
if (storage !== null) { | |
if (Array.isArray(storage)) { | |
storage.push(value) | |
} else { | |
storage = [storage]; | |
} | |
this.set(key, storage); | |
} else { | |
this.set(key, value); | |
} | |
} | |
/** | |
* Writes an Item into Storage | |
* @param {*} key | |
* @param {*} value | |
*/ | |
static set(key, value) { | |
localStorage.setItem(key, JSON.stringify(value)); | |
} | |
/** | |
* Get from LocalStorage | |
* @param {*} key | |
*/ | |
static get(key) { | |
return JSON.parse(localStorage.getItem(key)); | |
} | |
/** | |
* Searches an Item by ID in given Storage | |
* @param {*} key | |
* @param {*} id | |
*/ | |
static find(key, id) { | |
let storage = this.get(key); | |
if (Array.isArray(storage)) { | |
for (let item of storage) { | |
return (item.id === id) ? item : null; | |
} | |
} | |
} | |
/** | |
* Finds an Entry in Storage and updates it with given updatedItem | |
* @param {*} key | |
* @param {*} id | |
* @param {*} updatedItem | |
*/ | |
static update(key, id, updatedItem) { | |
let storage = this.get(key); | |
for (let entry in storage) { | |
if (storage[entry].id === id) { | |
storage[entry] = updatedItem; | |
} | |
} | |
this.set(key, storage); | |
} | |
static synced(value) { | |
this.set('synced', value); | |
} | |
static isSynced() { | |
return this.get('synced'); | |
} | |
} | |
export default Storage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Marten, me and my friend took part at your workshop on Saturday 03. November at SAE.
It would be awesome if you could upload the vue app you did in the workshop so we can have a look at the vue.js features again.
Thanks in advance. Theo