All files / src/shared/lib/lang l10n.ts

89.29% Statements 25/28
92.31% Branches 12/13
80% Functions 4/5
88% Lines 22/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                        129x 129x   129x 7x 10987x   7x     129x       129x 13302x 13302x 13311x 13311x 13311x   13302x     129x 76127x     76127x 76127x 76127x 13298x   62829x         129x  
import en from "lang/en.json";
 
export interface L10NLookup {
  [key: string]: string | boolean | undefined;
}
 
export interface L10NParams {
  [key: string]: string | number | undefined;
}
 
export type L10NKey = keyof typeof en;
 
const l10nStrings: L10NLookup = {};
let hasInit = false;
 
export const setL10NData = (data: L10NLookup) => {
  for (const key in data) {
    l10nStrings[key] = data[key];
  }
  hasInit = true;
};
 
export const getL10NData = () => {
  return l10nStrings;
};
 
export const replaceParams = (string: string, params: L10NParams) => {
  let outputString = string;
  Object.keys(params).forEach((param) => {
    const pattern = new RegExp(`{${param}}`, "g");
    const paramValue = String(params[param] ?? "");
    outputString = outputString.replace(pattern, paramValue);
  });
  return outputString;
};
 
const l10n = (key: L10NKey, params?: L10NParams): string => {
  Iif (!hasInit && process.env.NODE_ENV !== "test") {
    console.warn(`L10N used before initialisation for key "${key}"`);
  }
  const l10nString = l10nStrings[key] ?? key;
  if (typeof l10nString === "string") {
    if (params) {
      return replaceParams(l10nString, params);
    }
    return l10nString;
  }
  return String(l10nString);
};
 
export default l10n;