Skip to content

Instantly share code, notes, and snippets.

@dehypnosis
Last active June 26, 2020 02:19
Show Gist options
  • Save dehypnosis/7a63760065a33d0d92f65a5d6c3810e2 to your computer and use it in GitHub Desktop.
Save dehypnosis/7a63760065a33d0d92f65a5d6c3810e2 to your computer and use it in GitHub Desktop.
size of js object
const getSizeOfObject = obj => {
const typeSizes = {
"undefined": () => 0,
"boolean": () => 4,
"number": () => 8,
"string": item => 2 * item.length,
"object": item => !item ? 0 : Object
.keys(item)
.reduce((total, key) => sizeOf(key) + sizeOf(item[key]) + total, 0)
};
const sizeOf = value => typeSizes[typeof value](value);
const formatByteSize = bytes => {
if(bytes < 1024) return bytes + " bytes";
if(bytes < 1048576) return (bytes / 1024).toFixed(3) + " KiB";
if(bytes < 1073741824) return (bytes / 1048576).toFixed(3) + " MiB";
return (bytes / 1073741824).toFixed(3) + " GiB";
};
return formatByteSize(sizeOf(obj));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment