L10n: Improve code in JavaScript tr function

This commit is contained in:
Maxim Leshchenko 2021-12-22 19:09:05 +02:00
parent 3d44361a76
commit 21b03d3e71
No known key found for this signature in database
GPG key ID: BB9C44A8733FBEEE

View file

@ -1,36 +1,37 @@
function tr(string, ...arg) { function tr(string, ...args) {
let output = window.lang[string]; let output = window.lang[string];
if(arg.length > 0) { if(args.length > 0) {
if(typeof arg[0] == 'number') { if(typeof args[0] === "number") {
let numberedStringId; const cardinal = args[0];
let cardinal = arg[0]; let numberedString;
switch(cardinal) { switch(cardinal) {
case 0: case 0:
numberedString = string + '_zero'; numberedString = string + "_zero";
break; break;
case 1: case 1:
numberedString = string + '_one'; numberedString = string + "_one";
break; break;
default: default:
numberedString = string + (cardinal < 5 ? '_few' : '_other'); numberedString = string + (cardinal < 5 ? "_few" : "_other");
} }
let newoutput = window.lang[numberedString]; let newOutput = window.lang[numberedString];
if(newoutput === null) { if(newOutput === null)
newoutput = window.lang[string + '_other']; newOutput = window.lang[string + "_other"];
if(newoutput === null) {
newoutput = output; if(newOutput === null)
newOutput = output;
output = newOutput;
} }
} }
output = newoutput; if(output == null)
} return "@" + string;
}
for(const [ i, element ] of Object.entries(args))
output = output.replace(RegExp("(\\$" + (Number(i) + 1) + ")"), element);
let i = 1;
arg.forEach(element => {
output = output.replace(RegExp('(\\$' + i + ')'), element);
i++;
});
return output; return output;
} }