Skip to content

Instantly share code, notes, and snippets.

@gabefinch
Last active October 27, 2020 22:44
Show Gist options
  • Save gabefinch/7ba63049b934b1f01b3e4df3f075ddf1 to your computer and use it in GitHub Desktop.
Save gabefinch/7ba63049b934b1f01b3e4df3f075ddf1 to your computer and use it in GitHub Desktop.
export default class PersistentObject {
constructor(name, contents) {
this._validateContents(contents);
this.name = name;
this.contents = contents;
}
set(contents) {
this.contents = { ...contents };
localStorage.setItem(this.name, this.contents);
}
get() {
return localStorage.getItem(this.name) || this.contents;
}
setProperty(key, value) {
// Save a merged copy
this.set({ ...this.get(), [key]: value });
}
reset() {
this.set({});
localStorage.removeItem(this.name);
}
_validateContents(contents) {
if (typeof contents !== Object) {
throw TypeError('Contents must be an Object.');
}
}
_validateName(name) {
if (typeof name !== String) {
throw TypeError('Name must be a String.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment