Skip to content

Instantly share code, notes, and snippets.

@arbales
Created November 8, 2010 19:11
Show Gist options
  • Select an option

  • Save arbales/668112 to your computer and use it in GitHub Desktop.

Select an option

Save arbales/668112 to your computer and use it in GitHub Desktop.
Aids in interacting with the HTML5 localStorage API. Moved to a proper repo and fixed.
// ## StorageManager
// Aids in interacting with the HTML5 localStorage API.
StorageManager = {
// Returns the data associated with a key or `false` of no data exists.
get: function(key){
var data = localStorage.getItem(key);
if (data === "" || data === null){
return false;
} else {
var value = JSON.parse(data);
value.save = function(){
return StorageManager.set(value);
};
return value;
}
},
destroy: function(key){
return localStorage.removeItem(key);
},
all: function(){
var collection = [];
for (var i = 1; i < localStorage.length; i++){
collection.push(StorageManager.get(localStorage.key(i)));
}
return collection;
},
// Sets data to a key in localStorage or overwrites it if it exists. Returns the set value to act chainable.
// if you leave out the key, a UUID will be generated for you.
set: function(key, value){
if (value === undefined && (key.id === undefined)){
value = key;
key = StorageManager.uuid();
}else if (value === undefined && key.id !== undefined){
value = key;
key = value.id;
}
if (typeof value == 'object'){
value.id = key;
}
localStorage.setItem(key, JSON.stringify(value));
value.save = function(){
return StorageManager.set(value);
};
return value; // Look how easily that chains...
},
uuid: function(){
// http://www.ietf.org/rfc/rfc4122.txt
var s = [];
var hexDigits = "0123456789ABCDEF";
for (var i = 0; i < 32; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[12] = "4";
s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);
var uuid = s.join("");
return uuid;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment