Skip to content

Instantly share code, notes, and snippets.

@Dmitri-Sintsov
Last active December 15, 2024 09:30
Show Gist options
  • Save Dmitri-Sintsov/ff01ce67f083a785c2c5d3845d313927 to your computer and use it in GitHub Desktop.
Save Dmitri-Sintsov/ff01ce67f083a785c2c5d3845d313927 to your computer and use it in GitHub Desktop.
Web Storage with object key / value support.
class JsonStorage {
constructor(storage) {
this.storage = storage;
}
clear() {
this.storage.clear();
}
stringify(value) {
return (typeof value === 'string') ? value : JSON.stringify(value);
}
decode(value) {
try {
return JSON.parse(value);
} catch(e) {
return value;
}
}
getItem(keyName, defaultValue) {
let result = this.storage.getItem(this.stringify(keyName));
if (result === null) {
return (typeof defaultValue === 'undefined') ? null : defaultValue;
} else {
return this.decode(result);
}
}
len() {
return this.storage.length;
}
key(index) {
return this.storage.key(index);
}
removeItem(keyName) {
this.storage.removeItem(this.stringify(keyName));
}
setItem(keyName, keyValue) {
this.storage.setItem(
this.stringify(keyName),
this.stringify(keyValue)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment