mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import {I18n} from '@lingui/core'
2
3const truncateRounding = (num: number, factors: Array<number>): number => {
4 for (let i = factors.length - 1; i >= 0; i--) {
5 let factor = factors[i]
6 if (num >= 10 ** factor) {
7 if (factor === 10) {
8 // CA and ES abruptly jump from "9999,9 M" to "10 mil M"
9 factor--
10 }
11 const precision = 1
12 const divisor = 10 ** (factor - precision)
13 return Math.floor(num / divisor) * divisor
14 }
15 }
16 return num
17}
18
19const koFactors = [3, 4, 8, 12]
20const hiFactors = [3, 5, 7, 9, 11, 13]
21const esCaFactors = [3, 6, 10, 12]
22const itDeFactors = [6, 9, 12]
23const jaZhFactors = [4, 8, 12]
24const glFactors = [6, 12]
25const restFactors = [3, 6, 9, 12]
26
27export const formatCount = (i18n: I18n, num: number) => {
28 const locale = i18n.locale
29 let truncatedNum: number
30 if (locale === 'hi') {
31 truncatedNum = truncateRounding(num, hiFactors)
32 } else if (locale === 'ko') {
33 truncatedNum = truncateRounding(num, koFactors)
34 } else if (locale === 'es' || locale === 'ca') {
35 truncatedNum = truncateRounding(num, esCaFactors)
36 } else if (locale === 'ja' || locale === 'zh-CN' || locale === 'zh-TW') {
37 truncatedNum = truncateRounding(num, jaZhFactors)
38 } else if (locale === 'it' || locale === 'de') {
39 truncatedNum = truncateRounding(num, itDeFactors)
40 } else if (locale === 'gl') {
41 truncatedNum = truncateRounding(num, glFactors)
42 } else {
43 truncatedNum = truncateRounding(num, restFactors)
44 }
45 return i18n.number(truncatedNum, {
46 notation: 'compact',
47 maximumFractionDigits: 1,
48 // Ideally we'd use roundingMode: 'trunc' but it isn't supported on RN.
49 })
50}