|
- import numeral from 'numeral'
-
- type FormatFileSize = (n: number, raw?: boolean) => string
-
- const formatFileSize: FormatFileSize = (n, raw = false) => {
- if ((typeof n as unknown) !== 'number') {
- throw TypeError('Argument should be a number.')
- }
-
- if (isNaN(n)) {
- throw RangeError('Cannot format NaN.')
- }
-
- if (raw) {
- const absValue = Math.abs(n)
- const base = numeral(absValue < 1000 ? absValue : 999).format('0 b')
- const suffix = base.slice(base.indexOf(' ') + ' '.length)
- return `${n < 0 ? '-' : ''}${numeral(absValue).format('0,0')} ${suffix}`
- }
-
- const base = numeral(Math.abs(n)).format(Math.abs(n) < 1000 ? '0 b' : '0.00 b')
- return `${n < 0 ? '-' : ''}${base}`
- }
-
- export default formatFileSize
|