Last active
December 15, 2024 09:30
-
-
Save Dmitri-Sintsov/ff01ce67f083a785c2c5d3845d313927 to your computer and use it in GitHub Desktop.
Web Storage with object key / value support.
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 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