Last active
February 5, 2023 06:39
-
-
Save caderek/7f1f6fcae4ba8bd01491260655a83cf3 to your computer and use it in GitHub Desktop.
Simple wrapper for local and session storage
This file contains 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
/** | |
* 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