Last active
April 2, 2023 14:00
-
-
Save mmazzarolo/691041ea94bfe4c7109481c7bf4c5c72 to your computer and use it in GitHub Desktop.
Using JavaScript to fill localStorage to its maximum capacity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Fill localStorage to its maximum capacity. | |
* | |
* First, we find the highest order bit (the bit with the highest place value) | |
* that fits in localStorage by storing localStorage an increasingly big | |
* string of length 2, 4, 8, 16, etc. until it won't fill localStorage anymore. | |
* | |
* By working in iterations, starting with very long strings, and storing data | |
* in different items, we can keep a low memory profile and reduce the number of | |
* writes — making this process pretty fast. | |
* | |
* To cleanup localStorage you can use localStorage.clear(). Still, just in case | |
* you wanted to clean up only the data stored by this function (maybe because | |
* you want to keep in the localStorage the stuff you stored before running it), | |
* we return a convenient cleanup function. | |
* | |
* @return A cleanup function to delete the data we stored. | |
*/ | |
function fillLocalStorage(): () => void { | |
const key = "__filling_localstorage__"; | |
let max = 1; // This holds the highest order bit. | |
let data = "x"; // The string we're going to store in localStorage. | |
// Find the highest order bit by storing in localStorage an increasingly big | |
// string of length 2, 4, 8, 16, etc. (basically doubling its size and always | |
// follow a power of two) until it doesn't fill localStorage anymore. | |
try { | |
while (true) { | |
data = data + data; | |
localStorage.setItem(key, data); | |
max <<= 1; | |
} | |
} catch {} | |
// Then again, fill the rest of the space by increasing the string length | |
// in the opposite order of the one used above. | |
for (let bit = max >> 1; bit > 0; bit >>= 1) { | |
try { | |
localStorage.setItem(key, data.substring(0, max | bit)); | |
max |= bit; | |
} catch { | |
// Storage is now completely full 🍟 | |
} | |
} | |
// Cleanup | |
return function cleanup() { | |
localStorage.removeItem(key); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Snippet extracted from "Using JavaScript to fill localStorage to its maximum capacity"