Skip to content

Instantly share code, notes, and snippets.

@mmazzarolo
Last active April 2, 2023 14:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmazzarolo/691041ea94bfe4c7109481c7bf4c5c72 to your computer and use it in GitHub Desktop.
Save mmazzarolo/691041ea94bfe4c7109481c7bf4c5c72 to your computer and use it in GitHub Desktop.
Using JavaScript to fill localStorage to its maximum capacity
/**
* 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);
};
}
@mmazzarolo
Copy link
Author

mmazzarolo commented Jun 29, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment