forked from johnheroy/node-cc-cedict
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (87 loc) · 2.55 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
97
98
99
100
var _ = require('underscore');
var path = require('path');
var Sequelize = require('sequelize');
var sequelize = new Sequelize(null, null, null, {
dialect: 'sqlite',
storage: path.join(__dirname, './db/cc-cedict.sqlite')
});
var Word = sequelize.define('Word', {
traditional: Sequelize.STRING,
simplified: Sequelize.STRING,
pronunciation: Sequelize.STRING,
definitions: Sequelize.STRING
});
// 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};
}
Word
.findAll(query)
.then(function(words){
var results = [];
_.each(words, function(word){
var pronunciation = word.pronunciation;
var prettified = pinyin.prettify(pronunciation.slice(1, pronunciation.length - 1));
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,'');
if (numeric === "") {
part += "5";
newStr.push(part);
} else {
newStr.push(part);
}
});
str = "[" + newStr.join(" ") + "]";
var query = {
where: {pronunciation: str}
};
Word
.findAll(query)
.then(function(words) {
var results = [];
_.each(words, function(word) {
var pronunciation = word.pronunciation;
var prettified = pinyin.prettify(pronunciation.slice(1, pronunciation.length - 1));
results.push({
traditional: word.traditional,
simplified: word.simplified,
pronunciation: prettified,
definitions: word.definitions
});
});
cb(results);
});
}
module.exports.searchByEnglish = function(str, cb){
// TODO
};