Last active
August 3, 2022 00:30
-
-
Save EarMaster/cdccd62916990382814be3a7b6bd227e to your computer and use it in GitHub Desktop.
Formats a filesize into a human readable format. First parameter is filesize in bytes, second parameter is the precision of the resulting float and the last parameter is the system (choose between 'decimal' aka SI-based or 'binary' based calculation).
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
enum FileSizeSystems { | |
Decimal = 'decimal', | |
Binary = 'binary', | |
} | |
const formatFilesize = (size: number, decimals: number = 1, system: FileSizeSystems = FileSizeSystems.Decimal): string => { | |
const fileSizes = { | |
[FileSizeSystems.Decimal]: ['Byte', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], | |
[FileSizeSystems.Binary]: ['Byte', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'], | |
} | |
const base = { | |
[FileSizeSystems.Decimal]: 1000, | |
[FileSizeSystems.Binary]: 1024, | |
} | |
const steps = size > 0 ? Math.floor(Math.log(size) / Math.log(base[system])) : 0 | |
return parseFloat((size / Math.pow(base[system], steps)).toFixed(decimals)) + ' ' + fileSizes[system][steps] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment