Fast Plural Rules
Evaluates locale-specific plural rules to identify the right plural form for a cardinal number, which represents an item count. Internationalization libraries can utilize it to choose the right localized string.
If you are looking for a library compiling and executing the declarative CLDR plural rules, see plural-rules. Generated programmatically for better reliability, but bigger and slower.
Table of Contents
Synopsis
import { getPluralFormForCardinalByLocale } from 'fast-plural-rules'
getPluralFormForCardinalByLocale('en', 1)
getPluralFormForCardinalByLocale('en', 2)
getPluralFormForCardinalByLocale('en', 5)
getPluralFormForCardinalByLocale('cs', 1)
getPluralFormForCardinalByLocale('cs', 2)
getPluralFormForCardinalByLocale('cs', 5)
localizeMessage('en', 'fileCount', 3)
localizeMessage('cs', 'fileCount', 3)
function localizeMessage (locale, messageKey, cardinal) {
const pluralForm = getPluralFormForCardinalByLocale(locale, cardinal)
const messageFormat = messages[locale][messageKey][pluralForm]
return messageFormat.replace('{0}', cardinal)
}
const messages = {
en: {
fileCount: [
"{0} file",
"{0} files"
],
}
cs: {
fileCount: [
"{0} soubor",
"{0} soubory",
"{0} souborů"
]
}
}
There is another full example using plural form names instead of numeric indexes like this:
const messages = {
en: {
fileCount: {
one: '{0} file',
other: '{0} files'
}
},
cs: {
fileCount: {
one: '{0} soubor',
few: '{0} soubory',
other: '{0} souborů'
}
}
}
Installation and Getting Started
This module can be installed in your project using NPM or Yarn. Make sure, that you use Node.js version 6 or newer.
$ npm i fast-plural-rules --save
$ yarn add fast-plural-rules
Functions are exposed as named exports, for example:
import { getPluralFormForCardinalByLocale } from 'fast-plural-rules'
You can read more about the module loading in other environments, like with ESM or in web browsers. Usage scenarios demonstrate applications of this library in typical real-world situations. Design concepts explain the approach to the correct internationalization of messages with cardinals taken by this library. Translators will read about plural rules for supported languages to be able to write the right plural forms to language packs. Finally, the API reference lists all functions with a description of their functionality.
Library Integrations
Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.
License
Copyright (c) 2018-2022 Ferdinand Prantl
Licensed under the MIT license.