Skip to content

Commit

Permalink
Add custom zero to i18n.tp
Browse files Browse the repository at this point in the history
  • Loading branch information
Rogermax committed Jun 26, 2024
1 parent babddb5 commit 39d5234
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 6 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ yarn add factorial-i18n
const translations = {
en: {
common: { hello: 'hello %{name}', },
beers: { one: '%{count} beer', other: '%{count} beers' }
beers: { zero: 'No beers :(', one: '%{count} beer', other: '%{count} beers' }
},
es: {
common: { hello: 'hola %{name}', },
beers: { one: '%{count} cerveza', other: '%{count} cervezas' }
beers: { zero: 'Sin cervezas!', one: '%{count} cerveza', other: '%{count} cervezas' }
}
}

Expand All @@ -32,8 +32,9 @@ const i18n = new I18n()
i18n.setTranslations(translations)
i18n.setLocale('es')
i18n.t('common.hello') // => Hola
i18n.tp('common.beers', { count: 0 }) // => 0 cervezas
i18n.tp('common.beers', { count: 0 }) // => Sin cervezas!
i18n.tp('common.beers', { count: 1 }) // => 1 cerveza
i18n.tp('common.beers', { count: 2 }) // => 2 cervezas
```

## Where is it used?
Expand Down
3 changes: 2 additions & 1 deletion __tests__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const mockedTranslations = {
es: {
hello: 'hola %{name}',
beers: {
zero: 'sin cervezas!',
one: '%{count} cerveza',
other: '%{count} cervezas'
},
Expand Down Expand Up @@ -152,7 +153,7 @@ describe('i18n', () => {
})

it('uses pluralizations correctly otherwise', () => {
expect(i18n.tp('beers', { count: 0 })).toBe('0 cervezas')
expect(i18n.tp('beers', { count: 0 })).toBe('sin cervezas!')
expect(i18n.tp('beers', { count: 1 })).toBe('1 cerveza')
expect(i18n.tp('beers', { count: 2 })).toBe('2 cervezas')
})
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"jest": { "preset": "ts-jest" },
"dependencies": {
"lodash": "^4.17.15",
"plurals-cldr": "1.0.3"
"plurals-cldr": "2.0.1"
},
"devDependencies": {
"@types/jest": "24.0.13",
Expand Down
5 changes: 4 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ export default class I18n {
}

const form = plural(this.locale, num)
const pluralPath = `${path}.${form}`
let pluralPath = `${path}.${form}`
if (num === 0 && this.getKey(`${path}.zero`) !== undefined) {
pluralPath = `${path}.zero`
}

return this.t(pluralPath, opts)
}
Expand Down

0 comments on commit 39d5234

Please sign in to comment.