-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
55 lines (49 loc) · 1.65 KB
/
app.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
const data = require('./data.json');
const parser = module.exports = {};
// attrs will contain firstName, lastName, fullName
parser.parseName = function (name) {
const tokens = name.trim().split(/\s+/).map(w => w.toProperCase());
const attrs = {};
if (!tokens.length) {
return attrs;
}
if (tokens.length === 1) {
attrs.firstName = token[0];
return attrs;
}
// check if chinese name first
for (token of tokens) {
if (data.chineseSurnames.includes(token)) {
return parseChineseName(tokens, token);
} else if (data.malaySurnames.includes(token)) {
return parseMalayName(tokens);
}
}
return attrs;
}
parseChineseName = function(tokens, surname) {
// parse names by number of words
const attrs = {};
switch(tokens.length) {
case 2:
// first last or last first
attrs.firstName = tokens.filter(w => w !== surname)[0];
attrs.lastName = surname;
break;
case 3:
// first first last, last first first, first last first (to fix)
const firstNames = tokens.filter(w => w !== surname);
attrs.firstName = firstNames.join(' ');
attrs.lastName = surname;
break;
case 4:
// first last mid mid or last mid mid first
break;
default:
}
return attrs;
}
// https://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};