Created
March 25, 2021 06:29
-
-
Save cristianp6/4468c99345207765bf2e501f1679440b to your computer and use it in GitHub Desktop.
Little helper containint bytes number to string label conversion and viceversa
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 SIZES = ['B', 'KB', 'MB', 'GB', 'TB'] | |
const bytesToSizeString = (bytes) => { | |
if (!+bytes || bytes < 0) { | |
return `0 ${SIZES[0]}` | |
} | |
const i = Math.floor(Math.log(bytes) / Math.log(1024)) | |
return `${parseInt((bytes / Math.pow(1024, i)), 10)} ${SIZES[i]}` | |
} | |
const sizeStringToBytes = (size) => { | |
if (!size || size < 0) { | |
return 0 | |
} | |
const value = (size || '').toString().split(' ') | |
return parseInt(value[0], 10) * Math.pow(2, (Math.abs(SIZES.indexOf(value[1])) * 10)) | |
} | |
export { bytesToSizeString, sizeStringToBytes } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment