class Cache {
constructor(isLocal = true) {
this.storage = isLocal ? localStorage : sessionStorage
}
setItem(key, value) {
if (!this.verify(key, "key")) return
if (this.verify(value, 'value')) {
this.storage.setItem(key, JSON.stringify(value))
}
}
getItem(key) {
if (this.verify(key,"key")) {
const value = this.storage.getItem(key)
if (value) {
return JSON.parse(value)
}
}
}
removeItem(key) {
if (this.verify(key, "key")) {
this.storage.removeItem(key)
}
}
clear() {
this.storage.clear()
}
key(index) {
if (this.verify(index, "index")) {
return this.storage.key(index)
}
}
length() {
return this.storage.length
}
verify(value, name) {
switch (value) {
case undefined:
throw new Error(`${name} is a undefined`)
break;
case null:
throw new Error(`${name} is a null`)
break;
default:
return true
}
}
}
const localCache = new Cache()
const sessionCache = new Cache(false)
console.log("项目中引入使用。。。")
//项目使用打开下方注释代码
// export {
// localCache,
// sessionCache
// }
console