Last active
April 4, 2021 21:52
-
-
Save brunoti/21888f627786f656415e7c2df4850764 to your computer and use it in GitHub Desktop.
collection abstraction for local storage
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
import uuid from 'an-uuid'; | |
import {find, filter, findIndex} from 'lodash'; | |
class Collection { | |
constructor(schema, collection = [], clearFirst) { | |
this.schema = schema; | |
if(clearFirst) { | |
this.clear(); | |
} | |
this.addMany(collection); | |
} | |
add(object) { | |
const schema = this.all(); | |
if(!object.id) { | |
object.id = uuid(); | |
} | |
schema.push(object); | |
this.sync(schema); | |
} | |
addMany(array) { | |
const schema = this.all(); | |
this.sync(schema.concat(array)); | |
return this; | |
} | |
find(search) { | |
return find(this.all(), search); | |
} | |
filter(search) { | |
return filter(this.all(), search); | |
} | |
update(search, update) { | |
const schema = this.all(); | |
const index = findIndex(schema, search); | |
if(!schema[index]) { | |
return false; | |
} | |
schema[index] = Object.assign(schema[index], update); | |
this.sync(schema); | |
return schema[index]; | |
} | |
remove(search) { | |
const all = this.all(); | |
const index = findIndex(all, search); | |
// Removing item from array | |
const removed = all.splice(index, 1); | |
this.sync(all); | |
return removed; | |
} | |
sync(collection) { | |
localStorage.setItem(this.schema, JSON.stringify(collection)) | |
return this; | |
} | |
all() { | |
return JSON.parse(localStorage.getItem(this.schema)) || []; | |
} | |
clear() { | |
localStorage.removeItem(this.schema); | |
return this; | |
} | |
} | |
export default Collection; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment