Skip to content
This repository was archived by the owner on Feb 5, 2025. It is now read-only.

Commit 4b7fbe1

Browse files
committed
Pptional mapLocale function added to parse() method. Now parses locales using either "_" or "-". pick() maps older Chinese locales to match script or region.
1 parent 03bac26 commit 4b7fbe1

File tree

3 files changed

+1342
-3
lines changed

3 files changed

+1342
-3
lines changed

index.js

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,18 @@ var isString = function(s){
44
return typeof(s) === 'string';
55
};
66

7-
function parse(al){
7+
function parse(al, mapLocale){
88
var strings = (al || "").match(regex);
9+
var mapLocale = mapLocale || function (x) { return x; }
10+
911
return strings.map(function(m){
1012
if(!m){
1113
return;
1214
}
1315

1416
var bits = m.split(';');
15-
var ietf = bits[0].split('-');
17+
var ietf = mapLocale(bits[0]);
18+
ietf = ietf.split('-');
1619
var hasScript = ietf.length === 3;
1720

1821
return {
@@ -28,6 +31,32 @@ function parse(al){
2831
});
2932
}
3033

34+
// zh-CN = Simplified script with Mandarin grammar = Chinese as written in China
35+
// zh-TW = Traditional script with Mandarin grammar = Chinese as written in Taiwan
36+
// zh-HK = Traditional script with Cantonese grammar = Chinese as written in Hong Kong
37+
38+
var newLocales = {
39+
// https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/dd997383(v=vs.100)
40+
'zh-cht': 'zh-Hant',
41+
'zh-chs': 'zh-Hans',
42+
43+
'zh-tw': 'zh-Hant-TW',
44+
'zh-hk': 'zh-Hant-HK',
45+
'zh-mo': 'zh-Hant-MO',
46+
47+
// https://gist.github.com/amake/0ac7724681ac1c178c6f95a5b09f03ce
48+
'zh-sg': 'zh-Hans-SG',
49+
'zh-cn': 'zh-Hans-CN'
50+
};
51+
52+
function mapLocalesDefault(oldLocale) {
53+
// some apps use "_" instead of "-".
54+
var newLocale = oldLocale.toLowerCase().replace(/_/g, '-');
55+
newLocale = newLocales[newLocale] || newLocale;
56+
// console.log(oldLocale, newLocale);
57+
return newLocale;
58+
}
59+
3160
function pick(supportedLanguages, acceptLanguage, options){
3261
options = options || {};
3362

@@ -36,7 +65,7 @@ function pick(supportedLanguages, acceptLanguage, options){
3665
}
3766

3867
if(isString(acceptLanguage)){
39-
acceptLanguage = parse(acceptLanguage);
68+
acceptLanguage = parse(acceptLanguage, options.mapLocales || mapLocalesDefault);
4069
}
4170

4271
var supported = supportedLanguages.map(function(support){

0 commit comments

Comments
 (0)