JadoJodo
1/23/2017 - 8:00 PM

Ever need to fill local storage with junk to simulate running out of memory? Me neither until today, but here's a snippet if you ever need t

Ever need to fill local storage with junk to simulate running out of memory? Me neither until today, but here's a snippet if you ever need to. Just paste it in the console and it'll fill whatever space is left. - Credit: https://github.com/Zmixon

(function() {

  var nbBytes = 32768,
      oneByte = 'x',
      totalBytesInserted = 0;
      
  function bump(input) {
    if (!input) input = 0;
    while (window.localStorage[input] !== undefined) {
      input++;
    }
    return input;
  }

  function repeat(string, length) {
    var result = '';
    for (var i = 0; i < length; i++) {
      result += string;
    }
    return result;
  }
  
  console.group('Memory Fill');
  console.groupCollapsed('Errors');
  
  for (var i = 0; nbBytes > 1; i++) {
    var myString = repeat(oneByte, nbBytes);
    try {
      if (window.localStorage[i]) i = bump(i)
      window.localStorage.setItem(i, myString);
      totalBytesInserted += nbBytes;
    } catch (e) {
      nbBytes = parseInt(nbBytes / 2, 10);
      console.error('Error: %o Trying nbBytes:', e, nbBytes);
    }
  }
  
  console.groupEnd('Errors');

  console.info('Inserted %i bytes', totalBytesInserted);
  
  console.groupEnd('Memory Fill');
})();