Web Storage (localStorage, sessionStorage, cookies)
What storage management practice is demonstrated in this code?
// Before storing large data
const calculateStorageUsage = () => {
let total = 0;
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
total += key.length + value.length;
}
return total;
};
const storageLimit = 5 * 1024 * 1024; // 5MB
const currentUsage = calculateStorageUsage();
const newDataSize = JSON.stringify(newData).length;
if (currentUsage + newDataSize > storageLimit) {
// Implement storage cleanup or compression
}
This code demonstrates storage quota monitoring and management: 1) It calculates current storage usage by iterating through all items, 2) It checks if new data would exceed the storage limit before storing, 3) It allows preemptive handling of storage limitations, 4) The calculation includes both key and value sizes, 5) It helps prevent QuotaExceededError exceptions, 6) This approach enables implementing cleanup strategies before reaching limits, 7) It's important for applications that store large amounts of data, 8) The pattern helps maintain reliable storage operations.