From 21b03d3e71d39adafc8b5c9ba9c02c4e2d822c23 Mon Sep 17 00:00:00 2001 From: Maxim Leshchenko Date: Wed, 22 Dec 2021 19:09:05 +0200 Subject: [PATCH] L10n: Improve code in JavaScript tr function --- Web/static/js/l10n.js | 47 ++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/Web/static/js/l10n.js b/Web/static/js/l10n.js index 8fb53d20..f24801b8 100755 --- a/Web/static/js/l10n.js +++ b/Web/static/js/l10n.js @@ -1,36 +1,37 @@ -function tr(string, ...arg) { +function tr(string, ...args) { let output = window.lang[string]; - if(arg.length > 0) { - if(typeof arg[0] == 'number') { - let numberedStringId; - let cardinal = arg[0]; + if(args.length > 0) { + if(typeof args[0] === "number") { + const cardinal = args[0]; + let numberedString; + switch(cardinal) { case 0: - numberedString = string + '_zero'; + numberedString = string + "_zero"; break; case 1: - numberedString = string + '_one'; + numberedString = string + "_one"; break; default: - numberedString = string + (cardinal < 5 ? '_few' : '_other'); + numberedString = string + (cardinal < 5 ? "_few" : "_other"); } - let newoutput = window.lang[numberedString]; - if(newoutput === null) { - newoutput = window.lang[string + '_other']; - if(newoutput === null) { - newoutput = output; - } - } + let newOutput = window.lang[numberedString]; + if(newOutput === null) + newOutput = window.lang[string + "_other"]; - output = newoutput; + if(newOutput === null) + newOutput = output; + + output = newOutput; } } - - let i = 1; - arg.forEach(element => { - output = output.replace(RegExp('(\\$' + i + ')'), element); - i++; - }); + + if(output == null) + return "@" + string; + + for(const [ i, element ] of Object.entries(args)) + output = output.replace(RegExp("(\\$" + (Number(i) + 1) + ")"), element); + return output; -} \ No newline at end of file +}