Skip to content

Instantly share code, notes, and snippets.

@pixelthing
Forked from DavidWells/localstorage-size.js
Last active June 13, 2017 10:06
Show Gist options
  • Save pixelthing/c00b6974e5f21ce859afdeff4882e468 to your computer and use it in GitHub Desktop.
Save pixelthing/c00b6974e5f21ce859afdeff4882e468 to your computer and use it in GitHub Desktop.
// CM: forked to address key size (not just value size), swapping between KB and MB, ordering by size and logging total localstorage size.
// based on answer to question
// http://stackoverflow.com/questions/4391575/how-to-find-the-size-of-localstorage
(function showLocalStorageSize() {
threshold = 256; // the point where we stop displaying KB and start with MB
function stringSizeBytes(str) {
return str.length * 2;
}
function toMB(bytes) {
return bytes / 1024 / 1024 ;
}
function toKB(bytes) {
return bytes / 1024 ;
}
function toSize(key) {
return {
name: key,
size: stringSizeBytes(localStorage[key]) + stringSizeBytes(key)
};
}
function toSizeKBMB(info) {
if (info.size > (threshold * 1024)) {
info.size = toSizeMB(info.size);
} else {
info.size = toSizeKB(info.size);
}
return info;
}
function toSizeKB(size) {
return toKB(size).toFixed(2) + ' KB';
return info;
}
function toSizeMB(size) {
return toMB(size).toFixed(2) + ' MB';
}
// LOG SIZE BY KEY
var keysArray = Object.keys(localStorage);
var sizes = keysArray.map(toSize);
sizes.sort(function(a,b) {
return a.size - b.size;
}).reverse();
sizes.map(toSizeKBMB);
console.table(sizes);
// LOG TOTAL SIZE
var total = 0;
keysArray.map(function(key) {
total += toSize(key).size;
});
total = (total > (threshold * 1024) ? toSizeMB(total) : toSizeKB(total) );
console.warn('TOTAL LOCALSTORAGE SIZE: ' + total);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment