| 3 | const SYN_DB = require('./synonyms') |
| 4 | |
| 5 | function Dictionary () { |
| 6 | this.vocabulary = [] |
| 7 | this.synonyms = {} |
| 8 | this.is_suggestions_enabled = true |
| 9 | this.is_synonyms_enabled = true |
| 10 | |
| 11 | this.start = function () { |
| 12 | this.synonyms = SYN_DB |
| 13 | this.build_synonyms() |
| 14 | this.update() |
| 15 | } |
| 16 | |
| 17 | this.add_word = function (s) { |
| 18 | const word = s.toLowerCase().trim() |
| 19 | const regex = /[^a-z]/gi |
| 20 | |
| 21 | if (regex.test(word) || word.length < 4) { return } |
| 22 | |
| 23 | this.vocabulary[this.vocabulary.length] = word |
| 24 | } |
| 25 | |
| 26 | this.build_synonyms = function () { |
| 27 | const time = performance.now() |
| 28 | |
| 29 | for (const targetWord in SYN_DB) { |
| 30 | const synonyms = SYN_DB[targetWord] |
| 31 | this.add_word(targetWord) |
| 32 | for (const wordID in synonyms) { |
| 33 | const targetParent = synonyms[wordID] |
| 34 | if (this.synonyms[targetParent] && this.synonyms[targetParent].constructor === Array) { |
| 35 | this.synonyms[targetParent][this.synonyms[targetParent].length] = targetWord |
| 36 | } else { |
| 37 | this.synonyms[targetParent] = [targetWord] |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | console.log(`Built ${Object.keys(this.synonyms).length} synonyms, in ${(performance.now() - time).toFixed(2)}ms.`) |
| 42 | } |
| 43 | |
| 44 | this.find_suggestion = function (str) { |
| 45 | const target = str.toLowerCase() |
| 46 | |
| 47 | for (const id in this.vocabulary) { |
| 48 | if (this.vocabulary[id].substr(0, target.length) !== target) { continue } |
| 49 | return this.vocabulary[id] |
| 50 | } |
| 51 | return null |
| 52 | } |
| 53 | |
| 54 | this.find_synonym = function (str) { |
| 55 | if (str.trim().length < 4) { return } |
| 56 | |
| 57 | const target = str.toLowerCase() |
| 58 | |
| 59 | if (this.synonyms[target]) { |
| 60 | return uniq(this.synonyms[target]) |
| 61 | } |
| 62 | |