Skip to content

Instantly share code, notes, and snippets.

@ulisesantana
Last active January 19, 2022 06:55
Show Gist options
  • Save ulisesantana/8bb0d6b02e675e6fb98480f06c9e0183 to your computer and use it in GitHub Desktop.
Save ulisesantana/8bb0d6b02e675e6fb98480f06c9e0183 to your computer and use it in GitHub Desktop.
Service for localStorage
function localStorageService() {
return {
get(itemName) {
const item = localStorage.getItem(itemName);
const numPatt = new RegExp(/^\d+$/);
const jsonPatt = new RegExp(/[\[\{].*[\}\]]/);
if(item){
if(jsonPatt.test(item)){
return JSON.parse(item);
}
else if(numPatt.test(item)) {
return parseFloat(item);
}
else {
return item;
}
}
else {
return null;
}
},
set(itemName, item) {
if(typeof item === "object"){
localStorage.setItem(itemName, JSON.stringify(item));
} else {
localStorage.setItem(itemName, item);
}
},
remove(itemName) {
localStorage.removeItem(itemName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment