2
0
mirror of https://github.com/frappe/books.git synced 2024-11-09 23:30:56 +00:00

refactor: deprecate undersore translate

This commit is contained in:
18alantom 2022-01-19 13:54:54 +05:30 committed by Alan
parent c0beade500
commit 132883ffb4

68
utils/translation.js Normal file
View File

@ -0,0 +1,68 @@
function stringReplace(str, args) {
if (!Array.isArray(args)) {
args = [args];
}
if (str == undefined) return str;
let unkeyed_index = 0;
return str.replace(/\{(\w*)\}/g, (match, key) => {
if (key === '') {
key = unkeyed_index;
unkeyed_index++;
}
if (key == +key) {
return args[key] !== undefined ? args[key] : match;
}
});
}
class TranslationString {
constructor(...args) {
this.args = args;
}
get s() {
return this.toString();
}
ctx(context) {
this.context = context;
return this;
}
#translate(segment) {
if (this.context) {
// do something
}
return segment;
}
#stitch() {
const strList = this.args[0];
const argList = this.args.slice(1);
return strList
.map((s, i) => this.#translate(s) + (argList[i] ?? ''))
.join('');
}
toString() {
return this.#stitch();
}
toJSON() {
return this.#stitch();
}
valueOf() {
return this.#stitch();
}
}
function T(...args) {
if (typeof args[0] === 'string') {
return stringReplace(args[0], args.slice(1));
}
return new TranslationString(...args);
}