pluralizer.go

 1package i18n
 2
 3// PluralForm represents the different plural categories.
 4type PluralForm int
 5
 6const (
 7	// Zero is used when count is exactly 0
 8	Zero PluralForm = iota
 9	// One is used for singular (typically count == 1)
10	One
11	// Two is used for dual (count == 2) in some languages
12	Two
13	// Few is used for small counts in some languages
14	Few
15	// Many is used for larger counts in some languages
16	Many
17	// Other is the default/fallback form
18	Other
19)
20
21// String returns the string representation of the plural form.
22func (p PluralForm) String() string {
23	switch p {
24	case Zero:
25		return "zero"
26	case One:
27		return "one"
28	case Two:
29		return "two"
30	case Few:
31		return "few"
32	case Many:
33		return "many"
34	case Other:
35		return "other"
36	default:
37		return "other"
38	}
39}
40
41// PluralFunc is a function that returns the appropriate plural form for a count.
42type PluralFunc func(n int) PluralForm
43
44// Pluralize returns the appropriate text from a message based on count and plural rules.
45func (m *Message) Pluralize(count int, pluralFunc PluralFunc) string {
46	if pluralFunc == nil {
47		pluralFunc = DefaultPlural
48	}
49	form := pluralFunc(count)
50	return m.GetText(form)
51}
52
53// DefaultPlural is a simple plural function (English-like: 1 = one, else = other).
54func DefaultPlural(n int) PluralForm {
55	if n == 1 {
56		return One
57	}
58	return Other
59}