-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie-service.js
39 lines (35 loc) · 941 Bytes
/
trie-service.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
const PTrie = require('dawg-lookup/lib/ptrie').PTrie;
const words = require('./words_with_frequency_and_translation_and_ipa.json');
const packed = require('./packed.json').content;
const spellchecker = require('./spell-checker.js');
const ptrie = new PTrie(packed);
const getSuggestions = (prefix) => {
let suggestion = ptrie
.completions(prefix)
.sort((a, b) => {
return (
(words[b] || {frequency: 0}).frequency -
(words[a] || {frequency: 0}).frequency
);
})
.slice(0, 30)
.map((word) => {
return {
...words[word],
word,
};
});
if (suggestion.length === 0) {
suggestion = spellchecker.suggest(prefix);
if (suggestion.length > 0) {
suggestion = suggestion.map((item) => {
return {
...words[item],
word: item.toLowerCase(),
};
});
}
}
return suggestion;
};
module.exports = getSuggestions;