Skip to content

Instantly share code, notes, and snippets.

@brunoti
Last active April 4, 2021 21:52
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 brunoti/21888f627786f656415e7c2df4850764 to your computer and use it in GitHub Desktop.
Save brunoti/21888f627786f656415e7c2df4850764 to your computer and use it in GitHub Desktop.
collection abstraction for local storage
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