Skip to content

Instantly share code, notes, and snippets.

@typerandom
Created February 11, 2020 16:24
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 typerandom/83a25e09691ab71121d788249f14f74b to your computer and use it in GitHub Desktop.
Save typerandom/83a25e09691ab71121d788249f14f74b to your computer and use it in GitHub Desktop.
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