3 * Handles the JavaScript side of translating strings
4 * in a way which fits with Laravel.
9 * Create an instance, Passing in the required translations
12 constructor(translations) {
13 this.store = translations;
17 * Get a translation, Same format as laravel's 'trans' helper
22 get(key, replacements) {
23 let text = this.getTransText(key);
24 return this.performReplacements(text, replacements);
28 * Get pluralised text, Dependant on the given count.
29 * Same format at laravel's 'trans_choice' helper.
35 getPlural(key, count, replacements) {
36 let text = this.getTransText(key);
37 let splitText = text.split('|');
39 let exactCountRegex = /^{([0-9]+)}/;
40 let rangeRegex = /^\[([0-9]+),([0-9*]+)]/;
42 for (let i = 0, len = splitText.length; i < len; i++) {
45 // Parse exact matches
46 let exactMatches = t.match(exactCountRegex);
47 console.log(exactMatches);
48 if (exactMatches !== null && Number(exactMatches[1]) === count) {
49 result = t.replace(exactCountRegex, '').trim();
53 // Parse range matches
54 let rangeMatches = t.match(rangeRegex);
55 if (rangeMatches !== null) {
56 let rangeStart = Number(rangeMatches[1]);
57 if (rangeStart <= count && (rangeMatches[2] === '*' || Number(rangeMatches[2]) >= count)) {
58 result = t.replace(rangeRegex, '').trim();
64 if (result === null && splitText.length > 1) {
65 result = (count === 1) ? splitText[0] : splitText[1];
68 if (result === null) result = splitText[0];
69 return this.performReplacements(result, replacements);
73 * Fetched translation text from the store for the given key.
75 * @returns {String|Object}
78 let splitKey = key.split('.');
79 let value = splitKey.reduce((a, b) => {
80 return a !== undefined ? a[b] : a;
83 if (value === undefined) {
84 console.log(`Translation with key "${key}" does not exist`);
92 * Perform replacements on a string.
93 * @param {String} string
94 * @param {Object} replacements
97 performReplacements(string, replacements) {
98 if (!replacements) return string;
99 let replaceMatches = string.match(/:([\S]+)/g);
100 if (replaceMatches === null) return string;
101 replaceMatches.forEach(match => {
102 let key = match.substring(1);
103 if (typeof replacements[key] === 'undefined') return;
104 string = string.replace(match, replacements[key]);
111 module.exports = Translator;