-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
53 lines (43 loc) · 1.41 KB
/
index.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
var data = require('unicode-mandarin-readings')
var surnameSubs = require('./surname-subs.json')
var romanizationSys = require('./romanization-pairs.json')
var removeDiacritics = require('diacritics').remove
module.exports = function (name, system) {
system = system || 'WG'
var chars = name.replace(/\s/g, '').split('')
var surnameLength = chars.length > 3 ? 2 : 1
var result = chars.map(function (word, i) {
// Should it be subbed?
if (i < surnameLength && Object.keys(surnameSubs).indexOf(word) >= 0) {
word = surnameSubs[word]
}
var unicode = 'U+' + word.charCodeAt(0).toString(16).toUpperCase()
return processString(data[unicode], system)
})
return formatName(result)
}
// ['a', 'b'] -> 'b a'
// ['a', 'b', 'c'] -> 'b-c a'
// ['a', 'b', 'c', 'd'] -> 'c-d a-b'
function formatName (arr) {
if (arr.length === 2) {
return arr[1] + ' ' + arr[0]
} else if (arr.length === 3) {
return arr[1] + '-' + arr[2] + ' ' + arr[0]
} else if (arr.length === 4) {
return arr[2] + '-' + arr[3] + ' ' + arr[0] + '-' + arr[1]
}
}
function processString (str, system) {
if (!str) {
throw new Error('Input contains non-Chinese characters')
}
str = removeDiacritics(str).toUpperCase()
// romanization system
if (system !== 'HANYU') {
str = romanizationSys[str][system]
}
// titleCase
str = str.charAt(0).toUpperCase() + str.slice(1, str.length).toLowerCase()
return str
}