Skip to content

Instantly share code, notes, and snippets.

@cristianp6
Created March 25, 2021 06:29
Show Gist options
  • Save cristianp6/4468c99345207765bf2e501f1679440b to your computer and use it in GitHub Desktop.
Save cristianp6/4468c99345207765bf2e501f1679440b to your computer and use it in GitHub Desktop.
Little helper containint bytes number to string label conversion and viceversa
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