All files / fuse-ui-shared/i18n index.ts

89.19% Statements 33/37
76.47% Branches 13/17
80% Functions 4/5
87.88% Lines 29/33
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 76 77 78 792x                                               2x 10x   10x     2x   7x 4x       4x 4x 4x 4x 7x 6x   7x 7x 1x   6x   7x 7x   4x   4x 1x     4x       7x 4x 4x                 2x 2x 2x    
import * as _ from 'underscore';
 
//tslint:disable:no-reserved-keywords
export interface Localized {
  value: string;
}
 
export interface LocalizationSpec {
  key: string;
  value: string;
  comment?: string;
  example?: string;
}
 
export interface NestedMap<T> {
  [key: string]: T | NestedMap<T>;
}
 
export type LocalizedStrings = NestedMap<Localized>;
 
function isSpec(x: object): x is LocalizationSpec {
  return Object.keys(x).indexOf('key') >= 0;
}
 
export function isLocalized(x: object): x is Localized {
  const keys = Object.keys(x);
 
  return keys && keys.length === 1 && keys[0] === 'value';
}
 
const templateRegex = /\{([0-9]+)\}/g;
 
export function formatString(fmt: string, ...args: any[]): string {
  Iif (args.length === 0) {
    return fmt;
  }
 
  let match = templateRegex.exec(fmt);
  let cur = 0;
  let sb = [];
  while (match) {
    if (match.index > cur) {
      sb.push(fmt.substr(cur, match.index - cur));
    }
    const arg = args[parseInt(match[1], 10)];
    if (_.isDate(arg)) {
      sb.push(arg.toISOString());
    } else {
      sb.push(arg);
    }
    cur = match.index + match[0].length;
    match = templateRegex.exec(fmt);
  }
  templateRegex.lastIndex = 0;
 
  if (cur < fmt.length) {
    sb.push(fmt.substr(cur));
  }
 
  return sb.join('');
}
 
//tslint:disable-next-line
export function __(arg: string | Localized | LocalizationSpec, ...rest: any[]): string {
  Eif (_.isString(arg)) {
    return formatString.apply(null, [arg, ...rest]);
  }
  if (isSpec(arg)) {
    // throw if we are running in production env
  }
 
  return formatString.apply(null, [arg.value, ...rest]);
}
 
export enum Locale {
  en = 'en',
  chs = 'chs'
}