@kevinwin/

translate

Nodejs

function that takes a translations object, a key delimited by '.' and a substitutions object for interpolation. Returns a match or the key.

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function translate(translations = {}, key = '', substitutions = {}) {
  const phraseBook = {};

  populatePhraseBook(translations);

  if (phraseBook[key] && typeof phraseBook[key] === 'string') return handleSubstitutions(phraseBook[key], substitutions);

  console.warn(`Missing translation for key: ${key}`);

  function populatePhraseBook(morePhrases, prefix = '') {
    for (const [key, phrase] of Object.entries(morePhrases)) {
      const prefixedKey = prefix ? `${prefix}.${key}` : key;
      if (typeof phrase === 'object') {
        populatePhraseBook(phrase, prefixedKey);
      } else {
        phraseBook[prefixedKey] = phrase;
      }
    }
  }

  function handleSubstitutions(string, substitutions = {}) {

    const interpolationRegex = /\{\{(.*?)\}\}/g;

    return string.replace(interpolationRegex, (expression, match) => {
      match = match.trim();
      return substitutions.hasOwnProperty(match) ? substitutions[match] : expression
    });
  }
}
node v10.16.0