-
-
Save ramnathv/300763539e0c250d46be to your computer and use it in GitHub Desktop.
Little getter/setter for localStorage: store( 'name', 'barney' ); store( 'name' ) === 'barney'; store.delete( 'name' ); store.has( 'name' ) === false
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
// Get / setter for local storage | |
function store( key, value ){ | |
if( arguments.length > 1 ){ | |
localStorage.setItem( key, JSON.stringify( value ) ) | |
return value | |
} | |
// Simultaneous getting / setting is bad. | |
// It is wasteful to continuously encode & then decompile JSON and never useful. | |
else { | |
const encoded = localStorage.getItem( key ) | |
// JSON parser fails violently when attempting to decode the string 'undefined'. | |
// null, NaN and other primitives are fine. | |
return encoded === 'undefined' ? undefined : JSON.parse( encoded ) | |
} | |
} | |
store.has = key => | |
// Really? Yes: localStorage.hasOwnProperty( 'length' ) === true, I kid you not | |
Object.keys( localStorage ).some( thing => thing === key ) | |
store.delete = key => | |
store.has( key ) && delete localStorage[ key ] | |
export default store |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment