src/docs/js/translations.js   A
last analyzed

Complexity

Total Complexity 8
Complexity/F 2

Size

Lines of Code 42
Function Count 4

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
wmc 8
c 1
b 0
f 0
nc 2
mnd 2
bc 6
fnc 4
dl 0
loc 42
rs 10
bpm 1.5
cpm 2
noi 0

4 Functions

Rating   Name   Duplication   Size   Complexity  
A Translator.get 0 14 3
A translations.js ➔ ??? 0 3 1
A translations.js ➔ Translator 0 10 2
A Translator.setLanguage 0 3 2
1
// mini translator
2
3
const TRANSLATIONS = {
4
    en: require('./translations/en').default,
5
    zh: require('./translations/zh').default
6
    //es: require('./translations/es').default
7
}
8
9
10
const Translator = function (translations, separator = '.') {
11
    this.separator = separator
12
    this.translations = translations
13
14
    let navigatorLang = window.navigator.language || window.navigator.userLanguage
15
    let selectedLang = window.location.search.match(/(?:[\?\&])(?:lang=)(\w{2})(?:&|$)/)
16
    let lang = selectedLang ? selectedLang[1] : navigatorLang
17
18
    this.setLanguage(lang)
19
}
20
21
Translator.prototype.setLanguage = function (lang) {
22
    this.lang = typeof this.translations[lang] !== 'undefined' ? lang : 'en'
23
}
24
25
Translator.prototype.get = function (route) {
26
    let parts = route.split(this.separator)
27
    let translation = this.translations[this.lang]
28
29
    for (let i = 0; i < parts.length; i++) {
30
        translation = translation[parts[i]]
31
        if (translation === undefined) {
32
            translation = '[Error: No Translation]'
33
            break
34
        }
35
    }
36
37
    return translation
38
}
39
40
window.Translator = new Translator(TRANSLATIONS)
41
42
export default function (n) {
43
    return window.Translator.get(n)
44
}