Last active
July 14, 2022 14:51
-
-
Save edgvi10/2527ea3ac470d5e3ea5baad9c2dd9422 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const isJson = (str) => { | |
try { JSON.parse(str); } | |
catch (e) { return false; } | |
} | |
export default localstorage = { | |
listAll: () => Object.keys(localStorage), | |
getAll: () => localstorage.get(localstorage.listAll()), | |
get: (key) => { | |
if (Array.isArray(key)) { | |
const object = {}; | |
for(const item of key) object[item] = localstorage.get(item); | |
return object; | |
} else if (typeof key === "string") { | |
const value = localStorage.getItem(key); | |
return (isJson(value)) ? JSON.parse(value) : value; | |
} | |
}, | |
save: (key, value) => { | |
if (typeof key === "object") | |
for (const item of Object.keys(key)) | |
localstorage.save(item, key[item]); | |
else if (typeof key === "string") | |
localStorage.setItem(key, (isJson(value)) ? JSON.stringify(value) : value); | |
}, | |
remove: (key) => (typeof key === "string") ? localStorage.removeItem(key) : key.map(k => localstorage.remove(k)), | |
}; |
This file contains hidden or 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
const isJson=(str)=>{try{JSON.parse(str)}catch(e){return!1}} | |
const localstorage={listAll:()=>Object.keys(localStorage),getAll:()=>localstorage.get(localstorage.listAll()),get:(key)=>{if(Array.isArray(key)){const object={};for(const item of key)object[item]=localstorage.get(item);return object}else if(typeof key==="string"){const value=localStorage.getItem(key);return(isJson(value))?JSON.parse(value):value}},save:(key,value)=>{if(typeof key==="object")for(const item of Object.keys(key))localstorage.save(item,key[item]);else if(typeof key==="string")localStorage.setItem(key,(isJson(value))?JSON.stringify(value):value)},remove:(key)=>(typeof key==="string")?localStorage.removeItem(key):key.map(k=>localstorage.remove(k)),} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use Cases: