-
Notifications
You must be signed in to change notification settings - Fork 9
/
plurals.js
67 lines (54 loc) · 1.83 KB
/
plurals.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
(function plurals() {
// Depends on Intl.PluralRules implemented or polyfilled (browser support still spotty at the time of writing)
// Make sure your game's `<html>` tag has proper `lang` attribute (defaults to 'en')
// See plurals-ru.js and plurals-en.js for versions that work anywhere
'use strict';
const localeTag = document.documentElement.getAttribute('lang') || 'en';
const pluralRules = new Intl.PluralRules(localeTag);
const indices = {
ru: {
one: 0, // singular
many: 1, // plural
few: 2, // 2-4
},
en: {
one: 0, // singular
other: 1, // plural or zero
},
// TODO: add more languages
};
// TODO: add more slavic languages here
indices.pl = indices.ua = indices.ru; // slavic languages share singular/paucal/plural rules
const langIndex = indices[localeTag] || indices.en;
/**
*
* @param {number} amount
* @param {string[]} cases For English: ['cat', 'cats]. For slavic languages: ['яблоко', 'яблок', 'яблока']
* @returns {string}
*/
function pluralize(amount, cases) {
const rule = pluralRules.select(amount);
const index = langIndex[rule];
return cases[index];
}
const amountRe = /\${amount}/mg;
const pluralRe = /\${plural}/mg;
function pluralizeFmt(cases, tpl) {
function fmt(amount, plural) {
return tpl
.replace(amountRe, amount)
.replace(pluralRe, plural);
}
return (amount) => {
const plural = pluralize(amount, cases);
return fmt(amount, plural);
};
}
window.scUtils = Object.assign(
window.scUtils || {},
{
pluralize,
pluralizeFmt,
}
);
}());