Skip to content

Instantly share code, notes, and snippets.

@davidsharp
Created April 6, 2023 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsharp/b5bfe5e0fca8655b526f43e84f44f845 to your computer and use it in GitHub Desktop.
Save davidsharp/b5bfe5e0fca8655b526f43e84f44f845 to your computer and use it in GitHub Desktop.
turns a byte count into an object which can be used to compose KB/MB/GB/TB/PB values
const getBytes = (bytes,{unit=null,binary=false,toFixed=1} = {}) => {
const divisor = binary?1024:1000;
let value = bytes;
let sizeLevel=-1;
const sizeArray=['KB','MB','GB','TB','PB'];
if(unit){
sizeLevel=sizeArray.indexOf(unit);
value=(bytes/Math.pow(divisor,sizeLevel+1)).toFixed(toFixed)
}
else while(value>=divisor){
value=(value/divisor);
if(value<100)value=value.toFixed(toFixed);
else value=Math.floor(value);
sizeLevel++;
}
if(sizeLevel<0)value = (value/divisor).toFixed(toFixed);
return {bytes,value,unit:sizeArray[sizeLevel]||'KB'};
}
// Returned object can be composed into a string like `${Number(obj.value).toLocaleString()} ${obj.unit}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment