Last active
October 27, 2020 22:44
-
-
Save gabefinch/7ba63049b934b1f01b3e4df3f075ddf1 to your computer and use it in GitHub Desktop.
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
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