Skip to content

Instantly share code, notes, and snippets.

@tamr
Created January 4, 2014 03:39
Show Gist options
  • Select an option

  • Save tamr/8251318 to your computer and use it in GitHub Desktop.

Select an option

Save tamr/8251318 to your computer and use it in GitHub Desktop.
var ls = {
getItem: function (key) {
var value = localStorage.getItem(key);
try {
value = JSON.parse(value);
} catch (error) {
value = value;
}
return value;
},
setItem: function (key, value) {
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
},
removeItem: function (key) {
localStorage.removeItem(key);
},
clear: function(pattern) {
if (pattern) {
for (var item in localStorage) {
if (item.match(pattern)) {
localStorage.removeItem(item);
}
}
} else {
localStorage.clear();
}
},
key: function (index) {
return localStorage.key(index);
},
size: function() {
return localStorage.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment