-
Notifications
You must be signed in to change notification settings - Fork 34
/
translate.js
82 lines (67 loc) · 2.32 KB
/
translate.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
var translate = {}
, util = require('./util')
, code = require('./Mandarin.json')
/* translate Chinese word into English letter
* @param `chinese` {String} Chinese words or whatever
* @param [optional] `separator` {String} separator for the letters
* @param [optional] `callback(err, result)` {Function} if a callback is specified,
* the program will use an async way to do the translation
* @return `result` or `undefined [if a callback is specified]`
* @example
* var han = require('han');
* han.letter('中文') // zhong wen
* han.letter('中文', '-') // zhong-wen
* han.letter('中文', function(err, result){
* console.log(result) // zhong wen
* })
*/
translate.letter = function(){
var args = [].slice.call(arguments)
, originalArgs = args.slice()
, chinese = args.shift()
, last = args.pop()
, separator, make
if(!originalArgs.length) return '';
callback = last && util.jsType(last) === 'Function' ? last : null;
// consider the '0' in javascript and etc.
separator = args.length ? args[0] : callback !== last && last ? last : '';
make = require('./make')
return callback ? callback.call(this, null, make(chinese, code, separator)) :
make(chinese, code, separator);
}
/* translate Chinese into Pinyin(letters with notation)
* @param `chinese` {String} Chinese words or wahtever
*/
translate.pinyin = function(chinese){
if(!chinese) return [];
if(!util.isChinese(chinese)) return [chinese];
var words = util.toArray(chinese)
, phoneticize = require('./phoneticize')
, hanzi, result
// find out chinese words
hanzi = words.filter(function(word){
return util.isChinese(word);
})
// phoneticize notation
hanzi.forEach(function(word){
var key = escape(word).slice(2)
, pinyin = code[key].split(/\s+/)
words[words.indexOf(word)] = phoneticize(pinyin);
})
// concat non-chinese words
words.reduce(function(prev, cur, i){
if(util.jsType(prev) !== 'Array' && util.jsType(cur) !=='Array') {
prev = prev || '';
// remember the numbers
words[i] = prev + '' + cur;
util.jsType(words[--i]) !== 'Array' && (words[i] = '');
return prev + '' + cur;
}
})
// generate return value
result = words.filter(function(item){
return item.length;
})
return result;
}
module.exports = exports = translate;