Skip to content

Instantly share code, notes, and snippets.

@edgvi10
Created July 22, 2022 20:58
Show Gist options
  • Save edgvi10/f69bb8968436e7954258b1155ebc85a1 to your computer and use it in GitHub Desktop.
Save edgvi10/f69bb8968436e7954258b1155ebc85a1 to your computer and use it in GitHub Desktop.

Use Cases:

localstorage.listAll(); // list all keys
localstorage.getAll(); // get all keys
localstorage.get("key"); // return one value
localstorage.get(["key1", "key2"]); // return object of values
localstorage.save("key", "value"); // save one value
localstorage.save({"key1": "value1", "key2": "value2"}); // save multiple values
localstorage.remove("key"); // remove one value
localstorage.remove(["key1", "key2"]); // remove multiple values
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)),
};
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