Skip to content

Instantly share code, notes, and snippets.

@korczis
Last active December 28, 2015 05:39
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 korczis/7451199 to your computer and use it in GitHub Desktop.
Save korczis/7451199 to your computer and use it in GitHub Desktop.
Really simple localStorage wrapper - depends on modernizr
var storage = {
_impl: null,
// https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
implementationDummy: {
getItem: function(sKey) {
if (!sKey || !this.hasOwnProperty(sKey)) {
return null;
}
return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
},
key: function(nKeyId) {
return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]);
},
setItem: function(sKey, sValue) {
if (!sKey) {
return;
}
document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
this.length = document.cookie.match(/\=/g).length;
},
length: document.cookie.match(/\=/g).length,
removeItem: function(sKey) {
if (!sKey || !this.hasOwnProperty(sKey)) {
return;
}
document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
this.length--;
},
hasOwnProperty: function(sKey) {
return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
}
},
implementationReal: {
getItem: function(key) {
return localStorage.getItem(key);
},
setItem: function(key, value) {
return localStorage.setItem(key, value);
},
removeItem: function(key) {
return localStorage.removeItem(key);
}
},
initialize: function() {
if (Modernizr.localstorage) {
this._impl = this.implementationReal;
} else {
this._impl = this.implementationDummy;
}
},
get: function(key) {
if (!this._impl) {
this.initialize();
}
return JSON.parse(this._impl.getItem(key));
},
set: function(key, value) {
if (!this._impl) {
this.initialize();
}
return this._impl.setItem(key, JSON.stringify(value));
},
remove: function(key) {
if (!this._impl) {
this.initialize();
}
return this._impl.removeItem(key);
}
};
// Initialize
storage.initialize();
// EXAMPLE 1: Simple Set / Get
storage.set('user.name', 'Joe Doe');
storage.set('user.age', 42);
// Get by Key
storage.get('user.name');
storage.get('user.age');
// EXAMPLE 2: Complex Set / Get
var user = {
name: "Joe Doe",
age: 42,
address: {
stret: "35th Ave 2026",
city: "New York",
country: "United States of America"
}
};
// Write user to storage
storage.set('user', user);
// Get user from storage
var tmp = storage.get('user');
// Get Key
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment