Skip to content

Instantly share code, notes, and snippets.

@krrishd
Last active December 30, 2016 22:18
Show Gist options
  • Save krrishd/859c59c1cce42761d460e3726d415801 to your computer and use it in GitHub Desktop.
Save krrishd/859c59c1cce42761d460e3726d415801 to your computer and use it in GitHub Desktop.
A basic localStorage ORM
class LocalStore {
constructor(storeName) {
this.storeName = storeName;
localStorage[storeName] = JSON.stringify([]);
}
getAll() {
return JSON.parse(
localStorage[this.storeName]
);
}
setAll(mutatedStore) {
localStorage[this.storeName] = JSON.stringify(mutatedStore);
}
getItemByIndex(index) {
let storeObject = this.getAll();
return storeObject[index];
}
setItemByIndex(index, mutatedItem) {
let storeObject = this.getAll();
let mutatedStoreObject = storeObject;
mutatedStoreObject[index] = mutatedItem;
this.setAll(mutatedStoreObject);
}
getItemsByProperty(propertyKey, matchingValue) {
let storeObject = this.getAll();
let results = storeObject.filter(item => {
return item[propertyKey] === matchingValue;
});
return results;
}
setItemByProperty(propertyKey, matchingValue, modifiedItem) {
let storeObject = this.getAll();
let indexOfitemToModify = storeObject.findIndex(item => {
return item[propertyKey] == matchingValue;
});
storeObject[indexOfitemToModify] = modifiedItem;
this.setAll(storeObject);
}
addItem(item) {
let storeObject = this.getAll();
storeObject.push(item);
this.setAll(storeObject);
}
removeItem(item) {
let storeObject = this.getAll();
storeObject.splice(
storeObject.indexOf(item),
1
);
this.setAll(storeObject);
}
delete() {
localStorage.removeItem(this.storeName);
}
reset() {
localStorage[this.storeName] = JSON.stringify([]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment