Skip to content

Instantly share code, notes, and snippets.

@ahmednuaman
Created July 17, 2012 14:43
Show Gist options
  • Save ahmednuaman/3129819 to your computer and use it in GitHub Desktop.
Save ahmednuaman/3129819 to your computer and use it in GitHub Desktop.
A localStorage wrapper for HTML5 and shit
var Storage = function(name, callback)
{
var cache = { };
var keysIndex = '_' + name + '_';
var write = true;
// let's cache!
function _get(key)
{
var data = _.clone( cache[ key ] );
if ( !data && write )
{
try
{
data = JSON.parse( window.localStorage.getItem( key ) );
}
catch (e)
{
data = null;
}
}
return data;
}
function _remove(key)
{
if ( write )
{
try
{
window.localStorage.removeItem( key );
}
catch (e)
{
// nothing...
}
}
delete cache[ key ];
}
function _set(key, data)
{
if ( write )
{
try
{
window.localStorage.setItem( key, JSON.stringify( data ) );
}
catch (e)
{
// nothing...
}
}
cache[ key ] = data;
}
function key(id)
{
return name + '_' + id;
}
function getKey(index)
{
// get our keys
var keys = getKeys();
// check for id
var key = keys[ index ];
return key;
}
function getKeys()
{
// find our current keys hash
var data = _get( keysIndex );
// do we haz keys?
var keys = data ? data : [ ];
return keys;
}
function removeKey(index)
{
var keys = getKeys();
// check if we haz this key
if ( keys[ index ] )
{
keys.splice( index, 1 );
// sort them
keys.sort();
// save its ass
_set( keysIndex, keys );
}
}
function updateKeys(data)
{
var keys = getKeys();
// check if we need to add this key
if ( _.indexOf( keys, data.key ) === -1 )
{
keys.push( data.key );
// sort them
keys.sort();
// save its ass
_set( keysIndex, keys );
}
}
this.all = function(callback)
{
var all = [ ];
var keys = getKeys();
var data;
var id;
// loop through the data
for ( var i = 0; i < keys.length; i++ )
{
id = key( keys[ i ] );
data = _get( id );
all.push( data ? data : null );
}
// we've hit the end
callback( all );
}
this.get = function(id, callback)
{
// get the data using our name.key
var data = _get( key( id ) );
// parse it
var item = data ? data : null;
// send to callback;
callback( item );
}
this.save = function(data, callback)
{
// prepare an id for this data
var id = key( data.key );
// save its ass
_set( id, data );
// update our keys
updateKeys( data );
// callback!
if ( callback )
{
callback( data );
}
}
this.nuke = function()
{
var keys = getKeys();
var id;
// loop through the data
for ( var i = 0; i < keys.length; i++ )
{
_remove( id );
removeKey( i );
}
}
this.cache = function()
{
return cache;
}
this.setWriteToStorage = function(bool)
{
write = bool
}
callback();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment