forked from johnheroy/node-cc-cedict
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (85 loc) · 2.52 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
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
var _ = require('underscore');
var path = require('path');
var queryable = require( 'queryable' );
var db = queryable.open(path.resolve(__dirname, './db/cc-cedict.mongo'));
// convert between traditional and simplified
var cnchars = require('cn-chars');
// prettify the pinyin default (letters + numbers) in CC-CEDICT
var pinyin = require('prettify-pinyin');
module.exports.searchByChinese = function(str, cb){
var simplified = str.slice().split('');
var traditional = str.slice().split('');
for (var i = 0; i < str.length; i++){
simplified[i] = cnchars.toSimplifiedChar(str[i]);
traditional[i] = cnchars.toTraditionalChar(str[i]);
}
simplified = simplified.join('');
traditional = traditional.join('');
// default search is simplified unless input string is traditional
var query = {
where: {simplified: simplified}
};
if (traditional === str){
query.where = {traditional: traditional};
}
db.find(query.where, function(result) {
var results = [];
_.each(result.rows, function(word){
var pronunciation = word.pronunciation;
var prettified = pinyin.prettify(pronunciation.slice(1, pronunciation.length - 1).replace(/u\:/g, "v"));
results.push({
traditional: word.traditional,
simplified: word.simplified,
pronunciation: prettified,
definitions: word.definitions
});
});
cb(results);
});
};
module.exports.searchByPinyin = function(str, cb) {
// Catches dead-tones or 5th tone
var parts = str.split(" ");
var newStr = [];
_.each(parts, function(part) {
var numeric = part.replace(/\D/g,'');
// Convert ü/v to u: as used in dictionary
var newPart = [];
var umlat = false;
_.each(part.split(""), function(char) {
if (char === "ü" || char === "v") {
newPart.push("u");
newPart.push(":");
umlat = true;
} else {
newPart.push(char);
}
});
if (umlat)
newStr.push(newPart.join(""));
if (numeric === "") {
part += "5";
newStr.push(part);
} else if (!umlat) {
newStr.push(part);
}
});
str = "[" + newStr.join(" ") + "]";
db.find({pronunciation: str}, function(result) {
var results = [];
_.each(result.rows, function(word){
var pronunciation = word.pronunciation;
var prettified = pinyin.prettify(pronunciation.slice(1, pronunciation.length - 1).replace(/u\:/g, "v"));
results.push({
traditional: word.traditional,
simplified: word.simplified,
pronunciation: prettified,
definitions: word.definitions
});
});
cb(results);
});
}
module.exports.searchByEnglish = function(str, cb){
// TODO
};