-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18n.js
88 lines (66 loc) · 1.62 KB
/
i18n.js
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
79
80
81
82
83
84
85
86
87
88
export default class i18n {
constructor (options) {
this.locales = Object.create({})
if (this.checkIsObject(options)) {
this.settings = Object.assign({
namespace: 'sikko-i18n'
}, options)
}
}
checkIsObject (obj) {
return (obj instanceof Object)
}
checkIsEqual (a, b) {
return JSON.stringify(a) === JSON.stringify(b)
}
parse (obj) {
return JSON.parse(obj)
}
find (path, def) {
const stringToPath = path => {
if (typeof path !== 'string') return path
let output = []
path.split('.').forEach(item => {
item.split(/\[([^}]+)\]/g).forEach(key => {
if (key.length > 0) output.push(key)
})
})
return output
}
path = stringToPath(path)
let current = this.locales
for (let i = 0; i < path.length; i++) {
if (!current[path[i]]) return def
current = current[path[i]]
}
return current
}
stringify (obj) {
return JSON.stringify(obj)
}
getLocale (key) {
const { namespace } = this.settings
const stored = localStorage.getItem(namespace)
if (this.checkIsEqual(this.locales, JSON.parse(stored))) {
return JSON.parse(stored)[key]
}
}
getLocales () {
const { namespace } = this.settings
if (store) {
return localStorage.getItem(this.parse(namespace))
} else {
return this.locales
}
}
setLocales (value) {
const { namespace } = this.settings
if (this.checkIsObject(this.locales)) {
this.locales = value
localStorage.setItem(
namespace,
this.stringify(this.locales)
)
}
}
}