Map으로 localStorage 래핑 — JSON.stringify(map) 은 {} 라서 [...map](엔트리 배열)으로 저장하고 new Map(entries) 로 되살린다1
class LocalStorageMap {
constructor(storageKey) {
this.storageKey = storageKey
this.map = this.loadFromStorage()
}
loadFromStorage() {
const data = localStorage.getItem(this.storageKey)
return data ? new Map(JSON.parse(data)) : new Map()
}
saveToStorage() {
localStorage.setItem(this.storageKey, JSON.stringify([...this.map]))
}
set(key, value) {
this.map.set(key, value)
this.saveToStorage()
}
get(key) {
return this.map.get(key)
}
delete(key) {
const result = this.map.delete(key)
this.saveToStorage()
return result
}
clear() {
this.map.clear()
localStorage.removeItem(this.storageKey)
}
}
- localStorage는 문자열만 저장 → JSON 직렬화 필수
- 출처당 5MiB — 넘으면
setItem이QuotaExceededError를 던진다2
Footnotes
-
JSON.stringify() - MDN: “Only enumerable own properties are visited. This means Map, Set, etc. will become “{}”.“ ↩
-
Storage quotas and eviction criteria - MDN: “Browsers can store up to 5 MiB of local storage, and 5 MiB of session storage per origin.” · “Once this limit is reached, browsers throw a
QuotaExceededErrorexception” ↩