Skip to content

Commit

Permalink
New Function: LanguageNameByCode (#31)
Browse files Browse the repository at this point in the history
* New Function: LanguageNameByCode

* Test added
  • Loading branch information
vorlif committed Dec 7, 2023
1 parent 2c8406b commit 6193a66
Show file tree
Hide file tree
Showing 4 changed files with 562 additions and 0 deletions.
27 changes: 27 additions & 0 deletions humanize/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,3 +322,30 @@ func ExampleWithNow() {
// 1 周,1 日
// 1 Woche, 1 Tag
}

func ExampleHumanizer_LanguageNameByCode() {
collection := humanize.MustNew(humanize.WithLocale(es.New(), zhHans.New(), de.New()))
for _, tag := range []language.Tag{language.English, language.SimplifiedChinese, language.Spanish} {
h := collection.CreateHumanizer(tag)
fmt.Println("Current language: ", h.Language())

for _, code := range []string{"de", "en"} {
fmt.Printf("%s: %s\n", code, h.LanguageNameByCode(code))
}

fmt.Println(strings.Repeat(" -", 20))
}
// Output:
// Current language: en
// de: German
// en: English
// - - - - - - - - - - - - - - - - - - - -
// Current language: zh-Hans
// de: 德语
// en: 英语
// - - - - - - - - - - - - - - - - - - - -
// Current language: es
// de: Alemán
// en: Inglés
// - - - - - - - - - - - - - - - - - - - -
}
18 changes: 18 additions & 0 deletions humanize/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,28 @@ import (
)

// LanguageName returns the name of the spoken language as called by the languages used.
//
// If no translation exists for the name of the language, the input is returned.
func (h *Humanizer) LanguageName(lang string) string {
return h.loc.Get(lang)
}

// LanguageNameByCode returns the name of a language for a language code
// in the national language of the Humanizer.
//
// If no language is known for the code, an empty string is returned.
// If a language is known, but no translations are available, the English name is returned.
//
// For example, if a Humanizer was created for French, 'Anglais' is returned for the code 'en'
// and the value 'Allemand' for the code 'de'.
func (h *Humanizer) LanguageNameByCode(code string) string {
info, ok := LocaleInfos[code]
if !ok {
return ""
}
return h.loc.Get(info.Name)
}

// Language returns the currently used language.
func (h *Humanizer) Language() language.Tag {
return h.loc.Language()
Expand Down
Loading

0 comments on commit 6193a66

Please sign in to comment.