locale.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. export namespace Locale {
  2. export function titlecase(str: string) {
  3. return str.replace(/\b\w/g, (c) => c.toUpperCase())
  4. }
  5. export function time(input: number): string {
  6. const date = new Date(input)
  7. return date.toLocaleTimeString(undefined, { timeStyle: "short" })
  8. }
  9. export function datetime(input: number): string {
  10. const date = new Date(input)
  11. const localTime = time(input)
  12. const localDate = date.toLocaleDateString()
  13. return `${localTime} · ${localDate}`
  14. }
  15. export function todayTimeOrDateTime(input: number): string {
  16. const date = new Date(input)
  17. const now = new Date()
  18. const isToday =
  19. date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth() && date.getDate() === now.getDate()
  20. if (isToday) {
  21. return time(input)
  22. } else {
  23. return datetime(input)
  24. }
  25. }
  26. export function number(num: number): string {
  27. if (num >= 1000000) {
  28. return (num / 1000000).toFixed(1) + "M"
  29. } else if (num >= 1000) {
  30. return (num / 1000).toFixed(1) + "K"
  31. }
  32. return num.toString()
  33. }
  34. export function duration(input: number) {
  35. if (input < 1000) {
  36. return `${input}ms`
  37. }
  38. if (input < 60000) {
  39. return `${(input / 1000).toFixed(1)}s`
  40. }
  41. if (input < 3600000) {
  42. const minutes = Math.floor(input / 60000)
  43. const seconds = Math.floor((input % 60000) / 1000)
  44. return `${minutes}m ${seconds}s`
  45. }
  46. if (input < 86400000) {
  47. const hours = Math.floor(input / 3600000)
  48. const minutes = Math.floor((input % 3600000) / 60000)
  49. return `${hours}h ${minutes}m`
  50. }
  51. const hours = Math.floor(input / 3600000)
  52. const days = Math.floor((input % 3600000) / 86400000)
  53. return `${days}d ${hours}h`
  54. }
  55. export function truncate(str: string, len: number): string {
  56. if (str.length <= len) return str
  57. return str.slice(0, len - 1) + "…"
  58. }
  59. export function truncateMiddle(str: string, maxLength: number = 35): string {
  60. if (str.length <= maxLength) return str
  61. const ellipsis = "…"
  62. const keepStart = Math.ceil((maxLength - ellipsis.length) / 2)
  63. const keepEnd = Math.floor((maxLength - ellipsis.length) / 2)
  64. return str.slice(0, keepStart) + ellipsis + str.slice(-keepEnd)
  65. }
  66. export function pluralize(count: number, singular: string, plural: string): string {
  67. const template = count === 1 ? singular : plural
  68. return template.replace("{}", count.toString())
  69. }
  70. }