@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

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.42278626374739026","path":"index.js","file":{"path":"index.js","content":{"asEncoding":{"base64":"ZnVuY3Rpb24gdHJhbnNsYXRlKHRyYW5zbGF0aW9ucyA9IHt9LCBrZXkgPSAnJywgc3Vic3RpdHV0aW9ucyA9IHt9KSB7CiAgY29uc3QgcGhyYXNlQm9vayA9IHt9OwoKICBwb3B1bGF0ZVBocmFzZUJvb2sodHJhbnNsYXRpb25zKTsKCiAgaWYgKHBocmFzZUJvb2tba2V5XSAmJiB0eXBlb2YgcGhyYXNlQm9va1trZXldID09PSAnc3RyaW5nJykgcmV0dXJuIGhhbmRsZVN1YnN0aXR1dGlvbnMocGhyYXNlQm9va1trZXldLCBzdWJzdGl0dXRpb25zKTsKCiAgY29uc29sZS53YXJuKGBNaXNzaW5nIHRyYW5zbGF0aW9uIGZvciBrZXk6ICR7a2V5fWApOwoKICBmdW5jdGlvbiBwb3B1bGF0ZVBocmFzZUJvb2sobW9yZVBocmFzZXMsIHByZWZpeCA9ICcnKSB7CiAgICBmb3IgKGNvbnN0IFtrZXksIHBocmFzZV0gb2YgT2JqZWN0LmVudHJpZXMobW9yZVBocmFzZXMpKSB7CiAgICAgIGNvbnN0IHByZWZpeGVkS2V5ID0gcHJlZml4ID8gYCR7cHJlZml4fS4ke2tleX1gIDoga2V5OwogICAgICBpZiAodHlwZW9mIHBocmFzZSA9PT0gJ29iamVjdCcpIHsKICAgICAgICBwb3B1bGF0ZVBocmFzZUJvb2socGhyYXNlLCBwcmVmaXhlZEtleSk7CiAgICAgIH0gZWxzZSB7CiAgICAgICAgcGhyYXNlQm9va1twcmVmaXhlZEtleV0gPSBwaHJhc2U7CiAgICAgIH0KICAgIH0KICB9CgogIGZ1bmN0aW9uIGhhbmRsZVN1YnN0aXR1dGlvbnMoc3RyaW5nLCBzdWJzdGl0dXRpb25zID0ge30pIHsKCiAgICBjb25zdCBpbnRlcnBvbGF0aW9uUmVnZXggPSAvXHtceyguKj8pXH1cfS9nOwoKICAgIHJldHVybiBzdHJpbmcucmVwbGFjZShpbnRlcnBvbGF0aW9uUmVnZXgsIChleHByZXNzaW9uLCBtYXRjaCkgPT4gewogICAgICBtYXRjaCA9IG1hdGNoLnRyaW0oKTsKICAgICAgcmV0dXJuIHN1YnN0aXR1dGlvbnMuaGFzT3duUHJvcGVydHkobWF0Y2gpID8gc3Vic3RpdHV0aW9uc1ttYXRjaF0gOiBleHByZXNzaW9uCiAgICB9KTsKICB9Cn0="},"asBuffer":null},"loaded":true}}
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