Useful methods for file-related functions.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
840 B

  1. import numeral from 'numeral'
  2. type FormatFileSize = (n: number, raw?: boolean) => string
  3. const formatFileSize: FormatFileSize = (n, raw = false) => {
  4. if ((typeof n as unknown) !== 'number') {
  5. throw TypeError('Argument should be a number.')
  6. }
  7. if (isNaN(n)) {
  8. throw RangeError('Cannot format NaN.')
  9. }
  10. if (n < 0) {
  11. throw RangeError('Cannot format negative values.')
  12. }
  13. if (n === Number.POSITIVE_INFINITY) {
  14. throw RangeError('Cannot format infinity.')
  15. }
  16. if (raw) {
  17. const absValue = Math.abs(n)
  18. const base = numeral(absValue < 1000 ? absValue : 999).format('0 b')
  19. const suffix = base.slice(base.indexOf(' ') + ' '.length)
  20. return `${numeral(absValue).format('0,0')} ${suffix}`
  21. }
  22. return numeral(Math.abs(n)).format(Math.abs(n) < 1000 ? '0 b' : '0.00 b')
  23. }
  24. export default formatFileSize