Created
February 11, 2020 16:24
-
-
Save typerandom/83a25e09691ab71121d788249f14f74b to your computer and use it in GitHub Desktop.
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
class LocalStorageSet { | |
constructor(key, fifoMaxEntries = null) { | |
this.key = key; | |
this.fifoMaxEntries = fifoMaxEntries; | |
this.entries = this.load(); | |
} | |
load() { | |
const rawValue = window.localStorage.getItem( | |
this.key, | |
); | |
return JSON.parse(rawValue) || []; | |
} | |
persist() { | |
const entriesToPersist = [...this.entries]; | |
if (this.fifoMaxEntries !== null && entriesToPersist.length > this.fifoMaxEntries) { | |
entriesToPersist.shift(); | |
this.entries = entriesToPersist; | |
} | |
const serializedEntries = JSON.stringify( | |
entriesToPersist, | |
); | |
window.localStorage.setItem( | |
this.key, | |
serializedEntries, | |
); | |
} | |
contains(value) { | |
return this.entries.includes(value); | |
} | |
set(value) { | |
if (this.contains(value)) { | |
return false; | |
} | |
this.entries.push(value); | |
this.persist(); | |
return true; | |
} | |
} | |
const testStorage = new LocalStorageSet( | |
'testStorage', | |
5, | |
); | |
testStorage.set(1); | |
testStorage.set(2); | |
testStorage.set(3); | |
testStorage.set(4); | |
testStorage.set(5); | |
testStorage.set(6); | |
testStorage.set(7); | |
console.log('testStorage.contains(1)', testStorage.contains(1)); | |
console.log('testStorage.contains(7)', testStorage.contains(7)); | |
console.log(testStorage.entries); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment