Skip to content

Instantly share code, notes, and snippets.

@phiresky
Created September 24, 2015 11:35
Show Gist options
  • Save phiresky/3b70a5f036d53f311feb to your computer and use it in GitHub Desktop.
Save phiresky/3b70a5f036d53f311feb to your computer and use it in GitHub Desktop.
<script>
function log(s) {
document.writeln(s+"<br>");
console.log(s);
}
function generateString(bytes) {
return Array(bytes+1).join("a");
}
function binarySearch(boolFn, min, max) {
var mid = ((max + min) / 2)|0;
if(mid == min) return mid;
if(boolFn(mid)) return binarySearch(boolFn, mid, max);
else return binarySearch(boolFn, min, mid);
}
// test is between num/2 and nu
function binaryBracketSearch(test) {
var num = 1;
while(test(num)) num *= 2;
return num;
}
function test(num) {
log("testing "+num + " bytes (2^"+Math.log2(num)+")");
try {
localStorage.setItem("a", generateString(num));
localStorage.removeItem("a");
} catch(e) {
return false;
}
return true;
}
max = binaryBracketSearch(test);
log("result: "+binarySearch(test, (max/2)|0, max));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment