forked from nswbmw/rtrie
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
210 lines (187 loc) · 5.67 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
'use strict';
var vietnameseMap = [{
"a": ["à", "á", "ạ", "ả", "ã", "â", "ầ", "ấ", "ậ", "ẩ", "ẫ", "ă", "ằ", "ắ", "ặ", "ẳ", "ẵ"]
}, {
"e": ["è", "é", "ẹ", "ẻ", "ẽ", "ê", "ề", "ế", "ệ", "ể", "ễ"]
}, {
"i": ["ì", "í", "ị", "ỉ", "ĩ"]
}, {
"o": ["ò", "ó", "ọ", "ỏ", "õ", "ô", "ồ", "ố", "ộ", "ổ", "ỗ", "ơ", "ờ", "ớ", "ợ", "ở", "ỡ"]
}, {
"u": ["ù", "ú", "ụ", "ủ", "ũ", "ư", "ừ", "ứ", "ự", "ử", "ữ"]
}, {
"y": ["ỳ", "ý", "ỵ", "ỷ", "ỹ"]
}, {
"d": ["đ"]
}]
/**
* @class Rtrie
*
* @param {Object} options
* @param {String} options.trieKey the key prefixes for indexes
* @param {String|false} options.metadataKey the key prefixes for metadata, if `false`, not save metadata to redis
* @param {String} options.client redis client
* @param {String} options.host redis host(only `client` not exist)
* @param {String} options.port redis port(only `client` not exist)
* @param {String} options.password redis password(only `client` not exist)
*/
function Rtrie(options) {
var Redis = require('ioredis');
options = options || {};
this.trieKey = options.trieKey || 'trie:index:';
this.metadataKey = options.metadataKey === false ? false : (options.metadataKey || 'trie:metadata');
this.redis = options.client || new Redis(options);
}
/**
* add the `key` with a given `value` and `id` and `priority`.
*
* @param {String} key key for index
* @param {Object} value data you may want to store directly on the index.
* @param {String} id id for metadata
* @param {Number|Funcrion=>Number} priority the relevance of this item in comprassion of others.
* @return {Promise} Promise
* @api public
*/
Rtrie.prototype.add = function(key, value, id, priority) {
if (arguments.length < 3) {
return Promise.reject(new Error('`key` and `value` and `id` must be given!'));
}
priority = priority || function() {
return 0;
};
var _priority;
if ('number' === typeof priority) {
_priority = function() {
return priority;
};
} else if ('function' === typeof priority) {
_priority = priority;
} else {
return Promise.reject(new Error('`priority` must be number or function!'));
}
var redis = this.redis;
var trieKey = this.trieKey;
var metadataKey = this.metadataKey;
var parts = prefixes(key.toLowerCase());
var multi = redis.multi();
parts.forEach(function(part) {
multi.zadd(trieKey + part, _priority.call(null, key, value, id, part), id);
});
if (metadataKey !== false) {
multi.hset(metadataKey, id, JSON.stringify(value));
}
return multi.exec();
};
/**
* del the `key`.
*
* @param {String} key key for index
* @param {String} id id for metadata
* @return {Promise} Promise
* @api public
*/
Rtrie.prototype.del = function(key, id) {
if (!key || !id) {
return Promise.reject(new Error('`key` and `id` must be given!'));
}
var redis = this.redis;
var trieKey = this.trieKey;
var metadataKey = this.metadataKey;
var parts = prefixes(key.toLowerCase());
var multi = redis.multi();
parts.forEach(function(part) {
multi.zrem(trieKey + part, id);
});
if (metadataKey !== false) {
multi.hdel(metadataKey, id);
}
return multi.exec();
};
/**
* Searches for a key.
*
* @param {String} key the search key
* @param {Number} offset offset
* @param {Number} limit limit
* @return {Promise} Promise
* @api public
*/
Rtrie.prototype.search = function(key, offset, limit) {
if (!key) {
return Promise.reject(new Error('`key` must be given!'));
}
offset = offset || 0;
limit = limit || 20;
var indexKey = this.trieKey + normalize(key.trim().toLowerCase());
var redis = this.redis;
var metadataKey = this.metadataKey;
return redis.zrevrange(indexKey, offset, offset + limit - 1)
.then(function(ids) {
if (!ids.length) {
return [];
}
if (metadataKey === false) {
return ids;
}
return redis
.hmget(metadataKey, ids)
.then(function(metadatas) {
return metadatas.map(JSON.parse);
});
});
};
/**
Generate prefixes
*/
function replaceSpecialChars(string) {
return string.replace(/-/g, ' ')
}
function stringToPhrases(string) {
let words = string.split(' '),
phrases = [];
for (let i = 0; i < words.length; i++) {
let phrase = words[i];
for (let j = i + 1; j < words.length; j++) {
phrase += ' ' + words[j]
}
phrases.push(phrase);
}
return phrases
}
function tokenize(phrase) {
let prefixes = [],
prefix = '',
chars = phrase.split('');
for (let i = 0; i < chars.length; i++) {
prefix += chars[i];
if (prefix.trim() == prefixes.slice(-1).pop()) {
continue;
}
prefixes.push(prefix.trim())
}
return prefixes;
}
function prefixes(string) {
let prefixes = []
for (let phrase of stringToPhrases(normalize(string))) {
prefixes.push(...tokenize(phrase))
}
return prefixes;
}
// normalize a string with Vietnamese
// into non-accent mark
function normalize(string) {
string = replaceSpecialChars(string)
return string
.split('')
.map(char => {
for (let value of vietnameseMap) {
if (Object.values(value)[0].indexOf(char) > -1) {
return Object.keys(value)[0]
}
}
return char
})
.join('')
}
module.exports = Rtrie;