Created
April 6, 2023 10:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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