all files / lib/ index.js

96.3% Statements 26/27
95.83% Branches 23/24
100% Functions 15/15
96.3% Lines 26/27
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75              10× 10×                           10×     10×         10×     114×     40× 40×   40×         34×   34×                          
import Yandex from './yandex';
 
const translateKey = 'trnsl.1.1.20131018T175412Z.6e9fa29e525b4697.3542f82ffa6916d1ccd64201d8a72c023892ae5e';
const dictionaryKey = 'dict.1.1.20140616T070444Z.ecfe60ba07dd3ebc.9ce897a05d9daa488b050e5ec030f625d666530a';
 
const yandex = new Yandex(
  process.env.YANDEX_TRANSLATE_KEY || translateKey,
  process.env.YANDEX_DICTIONARY_KEY || dictionaryKey
);
 
export const translate = (fromLang, toLang, text, corrected = null) => {
  const translateFn = (text) => yandex.translate(fromLang, toLang, text);
  const translateFallback = () => translateFn(text)
    .then(translation => {
      if (translation === text && !corrected) {
        return yandex
          .spellCheck(fromLang, text)
          .then(onSpellResult);
 
        function onSpellResult(spellResult) {
          Iif (spellResult === text) {
            return { type: 'translate', result: translation, corrected };
          } else {
            return translate(fromLang, toLang, spellResult, spellResult);
          }
        };
      } else {
        return { type: 'translate', result: translation, corrected };
      }
    });
 
  const dictionary = () => yandex
    .dictionary(fromLang, toLang, text)
    .then(result => {
      if (result.length === 0) {
        return translateFallback();
      } else {
        return { type: 'dictionary', result: formatDictionary(result), corrected };
      }
    });
 
  return dictionary().then(null, translateFallback);
};
 
const joiner = (array, delimiter) => {
  return array.length > 0 ? '(' + array.join(' | ') + ')' : '';
};
 
const formatDictionaryTranslations = (translation) => {
  const synonyms = (translation.syn || []).map(syn => syn.text);
  const means = (translation.mean || []).map(means => means.text);
 
  return {
    translation: translation.text,
    synonyms: joiner(synonyms),
    means: joiner(means),
    examples: (translation.ex || []).map(function(ex) {
      const translations = ex.tr.map(_ => _.text);
 
      return {
        title: ex.text + ' ' + joiner(translations),
        text: ex.text,
        translations
      };
    })
  };
};
 
const formatDictionary = (result) => {
  return result.map(word => ({
    title: `${word.pos} (${word.ts})`,
    translations: word.tr.map(formatDictionaryTranslations)
  }));
};