| 1 |
import { __, sprintf } from '@wordpress/i18n'; |
| 2 |
|
| 3 |
export const formatFileSize = ( fileSizeInBytes, decimals = 2 ) => { |
| 4 |
const sizes = [ |
| 5 |
// translators: %s: file size in bytes |
| 6 |
__( '%s Bytes', 'image-optimization' ), |
| 7 |
// translators: %s: file size in kilobytes |
| 8 |
__( '%s Kb', 'image-optimization' ), |
| 9 |
// translators: %s: file size in megabytes |
| 10 |
__( '%s Mb', 'image-optimization' ), |
| 11 |
// translators: %s: file size in gigabytes |
| 12 |
__( '%s Gb', 'image-optimization' ), |
| 13 |
]; |
| 14 |
|
| 15 |
if ( ! fileSizeInBytes ) { |
| 16 |
// translators: %s: file size in bytes |
| 17 |
return sprintf( __( '%s Bytes', 'image-optimization' ), 0 ); |
| 18 |
} |
| 19 |
|
| 20 |
const currentScale = Math.floor( Math.log( fileSizeInBytes ) / Math.log( 1024 ) ); |
| 21 |
const formattedValue = parseFloat( ( fileSizeInBytes / Math.pow( 1024, currentScale ) ).toFixed( decimals ) ); |
| 22 |
|
| 23 |
// eslint-disable-next-line @wordpress/valid-sprintf |
| 24 |
return sprintf( sizes[ currentScale ], formattedValue ); |
| 25 |
}; |
| 26 |
|