All files / src/services/translation GoogleTranslateAPIParser.ts

100% Statements 14/14
100% Branches 2/2
100% Functions 5/5
100% Lines 14/14
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  2x     4x     1x 1x 1x 1x 1x     9x 9x 6x   3x     2x       58x       2x                                                    
/**
 * Type of response from free Google Translate API used by Google Translate
 * Chrome extension. There is probably no official documentation of it
 * on the internet, so this is only a aproximation.
 * 
 */
export type GoogleTranslateAPIResponse = [ [ [string, string, string, string, number] ], string, string ];
 
export class GoogleTranslateAPIParser {
  /**
   * 
   * @param separator Separator used in bath request
   */
  constructor(private separator: string) {}
  
  /**
   * Extract array of words from Google Translate API response
   * @param response JSON response from Google Translate API
   */
  parse(response: GoogleTranslateAPIResponse): Array<string> {
    console.log('ress', response)
    const translations = this.extractTranslations(response);
    console.log('transki', translations)
    const values = this.getTranslatedValues(translations);
    
    return values;
  }
 
  /**
   * Returns array of translation chunks
   * @param response JSON response from Google Translate API
   */
  extractTranslations(response: GoogleTranslateAPIResponse | Array<any>): Array<any> {
    const [first] = response;
 
    if (!Array.isArray(first)) {
      return first;
    }
 
    return first.map(this.extractTranslations);
  }
 
  /**
   * Returns array of values translated by Google
   * @param translations Array of translation chunks extracted by `extractTranslations` function
   */
  getTranslatedValues(translations: Array<string>): Array<string> {
    return translations
      .join('')
      .split(this.separator)
      .map(value => {
        return value.replace(/^\s|\s$/igm, '');
      });
  }
}