All files / src detect-lang.ts

100% Statements 13/13
100% Branches 6/6
100% Functions 1/1
100% Lines 13/13

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                                      2x 6x   6x   5x 5x 10x 4x 4x 10x 1x 1x   1x 1x  
/**
 * Get browser/nodejs language
 *
 * @returns BCP 47 tags of the browser/nodejs language
 */
export function detectLang(): string;
/**
 * Get browser/nodejs language that matches the given language tags
 *
 * @param langs The language tags to match (BCP 47 tags and sub-tags are supported)
 * @returns The first language tag that matches the browser/nodejs language, or `null` if no match
 *
 * @example
 * ```js
 * detectLang(["en", "zh-CN"]) || "zh-TW"
 * ```
 */
export function detectLang<T extends string>(langs: readonly T[]): T | null;
export function detectLang(langs: readonly string[]): string | null;
export function detectLang(langs?: readonly string[]): string | null {
  const locale = Intl.DateTimeFormat().resolvedOptions().locale;
 
  if (langs) {
    // BCP 47 tags are case-insensitive
    const lowerCaseLocale = locale.toLowerCase();
    for (const lang of langs) {
      if (lowerCaseLocale.startsWith(lang.toLowerCase())) {
        return lang;
      }
    }
    return null;
  }
 
  return locale;
}