Skip to content

Instantly share code, notes, and snippets.

@caderek
Last active February 5, 2023 06:39
Show Gist options
  • Save caderek/7f1f6fcae4ba8bd01491260655a83cf3 to your computer and use it in GitHub Desktop.
Save caderek/7f1f6fcae4ba8bd01491260655a83cf3 to your computer and use it in GitHub Desktop.
Simple wrapper for local and session storage
/**
* Simple wrapper for localStorage and sessionStorage,
* that takes care of data initialization, serialization and deserialization,
* so you can work with simple JSON-compatible values.
*/
function wrapStorage(storage, initialData = {}) {
const publicAPI = {
get size() {
return storage.length
},
keys() {
return Array.from({ length: this.size }, (_, i) => storage.key(i))
},
get(key) {
const item = storage.getItem(key)
return item === null ? undefined : JSON.parse(item)
},
getAll() {
return Object.fromEntries(this.keys().map((key) => [key, this.get(key)]))
},
set(key, value) {
storage.setItem(key, JSON.stringify(value))
},
remove: storage.removeItem.bind(storage),
clear: storage.clear.bind(storage),
}
for (const [key, value] of Object.entries(initialData)) {
if (storage.getItem(key) === null) {
publicAPI.set(key, value)
}
}
return publicAPI
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment