Skip to content

Instantly share code, notes, and snippets.

@phattranky
Forked from olafdietsche/fiddle.js
Created January 27, 2020 06:59
Show Gist options
  • Save phattranky/cb1750c1a7cdbef4d272c39b7e836bad to your computer and use it in GitHub Desktop.
Save phattranky/cb1750c1a7cdbef4d272c39b7e836bad to your computer and use it in GitHub Desktop.
Javascript: get localStorage maximum size
if (!localStorage) {
console.log('unavailable');
} else {
var max = 'x', s;
var lower_bound = 1, upper_bound = 1, middle;
// determine lower and upper bound
try {
while (true) {
localStorage.setItem('test', max);
lower_bound = upper_bound;
upper_bound *= 2;
max = max + max;
}
} catch (e) {
}
// do a binary search
while (upper_bound - lower_bound > 2) {
try {
middle = (lower_bound + upper_bound) / 2;
s = max.substr(0, middle);
localStorage.setItem('test', s);
lower_bound = middle;
} catch (e) {
upper_bound = middle;
}
}
console.log('size=' + lower_bound + '/' + upper_bound + '=' + (lower_bound / 1024).toFixed(1) + 'k');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment