-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathglobal.js
129 lines (109 loc) · 2.32 KB
/
global.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/**
* Flag if environment is Node JS
*
* @global
* @type {boolean}
*/
const isNodeJs = global.process && global.process.release && global.process.release.name === 'node';
/**
* Get ISO 639-1 language string
*
* @global
* @returns {string} ISO 639-1 language string
*/
function getLanguage() {
let lang;
if(global.isNodeJs) {
lang = process.env.LANGUAGE || process.env.LANG;
} else {
lang = navigator.language || navigator.languages && navigator.languages[0];
}
lang = lang.substr(0, 2);
return lang;
}
/**
* Tries to get country from language
*
* @global
* @returns {(string|null)} Country code or null if it couldn't find
*/
function getCountry() {
if(typeof global.userCountry !== 'undefined') {
return global.userCountry;
}
let country;
if(global.isNodeJs) {
country = process.env.LANG;
} else {
country = navigator.language;
if(country.length < 3 && navigator.languages) {
for(let i = 0; i < navigator.languages.length; i++) {
if(navigator.languages[i].length > 2) {
country = navigator.languages[i];
break;
}
}
}
}
const countryMatch = country.match(/^[a-z]{2}[_-]([A-Z]{2})/);
if(countryMatch !== null) {
country = countryMatch[1];
}
return country;
}
/**
* Check if given argument is numeric
*
* @global
* @param {*} n Subject of examination
* @returns {boolean} Verdict
*/
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* Parse value to proper type
*
* @global
* @param {*} value Value to be parsed
* @returns {number|boolean|object} Parsed value
*/
function parseValue(value) {
// check if it's even a string
if(typeof value !== 'string') {
return value;
}
// check if it's number
if (global.isNumeric(value)) {
return parseFloat(value);
}
// check if it's a boolean
const _value = value.toLowerCase();
if (_value === 'true' || _value === 'false') {
return _value === 'true';
}
// add more check here if you want
// return not parsed value in the end
return value;
}
/**
* MD5
*
* @global
* @method
* @param {string} String to be hashed
* @returns {string} Hash
*/
import md5 from'./md5';
export default {
constant: {
isNodeJs
},
static: {
getLanguage,
getCountry,
isNumeric,
parseValue,
md5
}
};