Last active
January 19, 2022 06:55
-
-
Save ulisesantana/8bb0d6b02e675e6fb98480f06c9e0183 to your computer and use it in GitHub Desktop.
Service for localStorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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