class translation { /** * @var {string} * This is translated content. */ #content; /** * @var {bool} * This is true, when content is translated from dict, and false * when could not being found. */ #translated; /** * This create new translation. Translation store content of the * translation, make avairable to format translated phrase and also * store that translation was found in the phrasebook. * * @param {string} content - Content of the translation. * @param {bool} translated - True when translation could be found. */ constructor(content, translated = true) { if (typeof(content) !== "string") { throw new TypeError("Translated content must be string."); } if (typeof(translated) !== "boolean") { throw new TypeError("Result of translation must be boolean."); } this.#content = content; this.#translated = translated; Object.freeze(this); } /** * This convert transiation to string. * * @returns {string} - Content of the translation. */ toString() { return this.#content; } /** * @returns {string} - Content of the translation. */ get text() { return this.#content; } /** * @returns {bool} - True when translation was found, false when not. */ get valid() { return this.translated; } /** * This would format ready translation, with numbers, dats, and * other content, which could not being statically places into * translation. To use it, place name of content object key into * "#{}" in translation. * * @example ``` * Translation: "I have more than #{how_many} apples!" * Object: { how_many: 10 } * Result: "I have more than 10 apples!" * ``` * * @param {string} content * @returns {string} */ format(content) { if (typeof(content) !== "object") { throw new TypeError("Content to format from must be object."); } if (!this.#translated) { return this.#content; } return this.#parse_format(content); } /** * This infill prepared translation with data from content * object. * * @see format * * @param {object} content - Content to load data from. * @returns {string} - Formater translation. */ #parse_format(content) { let parts = this.#content.split("#{"); let result = parts[0]; for (let count = 1; count < parts.length; ++count) { const part = parts[count]; const splited = part.split("}"); if (splited.length === 1) { return result + splited[0]; } const name = splited.splice(0, 1)[0].trim(); const rest = splited.join("}"); if (!(name in content)) { DEBUG: throw new RangeError( "Could not find \"" + name + "\"." ); result += rest; continue; } result += content[name] + rest; } return result; } } exports.translation = translation;