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.

format.ts 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * Formats a number with comma separators.
  3. * @example formatNumber(1234567) will return '1,234,567'
  4. * @example formatNumber(1234567.89) will return '1,234,567.89'
  5. */
  6. export const formatNumber = (num: number | string) => {
  7. if (!num)
  8. return num
  9. const parts = num.toString().split('.')
  10. parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  11. return parts.join('.')
  12. }
  13. /**
  14. * Format file size into standard string format.
  15. * @param fileSize file size (Byte)
  16. * @example formatFileSize(1024) will return '1.00KB'
  17. * @example formatFileSize(1024 * 1024) will return '1.00MB'
  18. */
  19. export const formatFileSize = (fileSize: number) => {
  20. if (!fileSize)
  21. return fileSize
  22. const units = ['', 'K', 'M', 'G', 'T', 'P']
  23. let index = 0
  24. while (fileSize >= 1024 && index < units.length) {
  25. fileSize = fileSize / 1024
  26. index++
  27. }
  28. return `${fileSize.toFixed(2)}${units[index]}B`
  29. }
  30. /**
  31. * Format time into standard string format.
  32. * @example formatTime(60) will return '1.00 min'
  33. * @example formatTime(60 * 60) will return '1.00 h'
  34. */
  35. export const formatTime = (seconds: number) => {
  36. if (!seconds)
  37. return seconds
  38. const units = ['sec', 'min', 'h']
  39. let index = 0
  40. while (seconds >= 60 && index < units.length) {
  41. seconds = seconds / 60
  42. index++
  43. }
  44. return `${seconds.toFixed(2)} ${units[index]}`
  45. }
  46. export const downloadFile = ({ data, fileName }: { data: Blob; fileName: string }) => {
  47. const url = window.URL.createObjectURL(data)
  48. const a = document.createElement('a')
  49. a.href = url
  50. a.download = fileName
  51. document.body.appendChild(a)
  52. a.click()
  53. a.remove()
  54. window.URL.revokeObjectURL(url)
  55. }
  56. export const snakeCase2CamelCase = (input: string): string => {
  57. return input.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
  58. }