面试官居然要我用JS代码计算LocalStorage容量!
作者:Sunshine_Lin
来源:SegmentFault 思否社区
前言
LocalStorage 容量
计算总容量
let str = '0123456789'
let temp = ''
// 先做一个 10KB 的字符串
while (str.length !== 10240) {
str = str + '0123456789'
}
// 先清空
localStorage.clear()
const computedTotal = () => {
return new Promise((resolve) => {
// 不断往 LocalStorage 中累积存储 10KB
const timer = setInterval(() => {
try {
localStorage.setItem('temp', temp)
} catch {
// 报错说明超出最大存储
resolve(temp.length / 1024 - 10)
clearInterval(timer)
// 统计完记得清空
localStorage.clear()
}
temp += str
}, 0)
})
}
(async () => {
const total = await computedTotal()
console.log(`最大容量${total}KB`)
})()
已使用容量
const computedUse = () => {
let cache = 0
for(let key in localStorage) {
if (localStorage.hasOwnProperty(key)) {
cache += localStorage.getItem(key).length
}
}
return (cache / 1024).toFixed(2)
}
(async () => {
const total = await computedTotal()
let o = '0123456789'
for(let i = 0 ; i < 1000; i++) {
o += '0123456789'
}
localStorage.setItem('o', o)
const useCache = computedUse()
console.log(`已用${useCache}KB`)
})()
剩余可用容量
const computedsurplus = (total, use) => {
return total - use
}
(async () => {
const total = await computedTotal()
let o = '0123456789'
for(let i = 0 ; i < 1000; i++) {
o += '0123456789'
}
localStorage.setItem('o', o)
const useCache = computedUse()
console.log(`剩余可用容量${computedsurplus(total, useCache)}KB`)
})()
评论