UNPKG

redscorpion-utils

Version:

A good JavaScript tools

1 lines 1.89 kB
import{set as jsonSet,get as jsonGet,remove as jsonRemove}from '../json/index.js';const prefix='scorpion-';const defaultName='default';export const set=(sName=defaultName,sValue='')=>{if(sName===''){console.assert(false,'[RS-STORAGE warn]: The name cannot be empty or empty string!');return}const arr=sName.split('.');const n0=`${arr[0]}`;let val=sValue;if(arr.length>1){const old=window.localStorage.getItem(`${ prefix }${ n0 }`);if(old===null){for(let i=arr.length-1;i>0;i-=1){if(i>0){const a0={};a0[arr[i]]=val;val=a0}}}else{const jsonData=JSON.parse(old);arr[0]='value';const newData=jsonSet(jsonData,arr.join('.'),sValue);val=newData[arr[0]]}}window.localStorage.setItem(`${ prefix }${ n0 }`,JSON.stringify({value:val}))};export const get=(sName=defaultName)=>{if(sName===''){console.assert(false,'[RS-STORAGE warn]: The name cannot be empty or empty string!');return null}const arr=sName.split('.');const n0=`${arr[0]}`;const value=window.localStorage.getItem(`${ prefix }${ n0 }`);if(value===null){return null}const jsonData=JSON.parse(value);arr[0]='value';return jsonGet(jsonData,arr.join('.'))};export const getToDefault=(sName=defaultName,defaultValue='')=>{const value=get(sName);if(value===null||value===''){return defaultValue}return value};export const remove=(sName=defaultName)=>{if(sName===''){console.assert(false,'[RS-STORAGE warn]: The name cannot be empty or empty string!');return}const arr=sName.split('.');const n0=`${arr[0]}`;if(arr.length===1){window.localStorage.removeItem(`${ prefix }${ n0 }`)}else{const value=window.localStorage.getItem(`${ prefix }${ n0 }`);if(value===null){return}const jsonData=JSON.parse(value);arr[0]='value';const newData=jsonRemove(jsonData,arr.join('.'));window.localStorage.setItem(`${ prefix }${ n0 }`,JSON.stringify(newData))}};export const clear=()=>{window.localStorage.clear()};export default{set,get,getToDefault,remove,clear};