UNPKG

@rr0/lang

Version:

Language and translation

49 lines 1.76 kB
import { Gender, ObjectUtils } from "@rr0/common"; export class Translator { /** * Creates a message translator to some language. * * @param locale The language to translate to. * @param grammar The grammar rules of the language. */ constructor(locale, grammar) { this.locale = locale; this.grammar = grammar; } compoundKey(subKeys) { return subKeys.sort().join('_'); } getGender(word) { return Gender[Object.keys(word)[0]]; } translateKey(obj, key, values = {}) { if (!obj.hasOwnProperty(key)) { throw Error(`No key "${key}" found in ${JSON.stringify(obj)}`); } return this.translate(obj[key], values); } /** * Returns a translated message, with possible values interpolated. * * @param template The message template, which can contain placeholders such as ${key} or ${key:plural} * @param values The values to be interpolated into the placeholders. */ translate(template, values = {}) { // assert.ok(Boolean(template), 'Translation requires a template') let translated = template; for (const key in values) { if (values.hasOwnProperty(key)) { const value = values[key]; if (ObjectUtils.isSet(value)) { translated = translated.replace(`\$\{${`${key}:plural`}\}`, this.grammar.plural(value)); translated = translated.replace(`\$\{${key}\}`, value); } } } if (translated.indexOf('${') > 0) { throw Error(`Parameter was not replaced in "${translated}"`); } return translated; } } //# sourceMappingURL=Translator.js.map