Skip to content

Instantly share code, notes, and snippets.

@ramnathv
Forked from barneycarroll/store.js
Created November 24, 2015 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramnathv/300763539e0c250d46be to your computer and use it in GitHub Desktop.
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
// 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