-
Notifications
You must be signed in to change notification settings - Fork 2
/
dictionary-trie.js
55 lines (45 loc) · 1.14 KB
/
dictionary-trie.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
import fs from 'fs';
class Dictionary {
constructor(fileName) {
this.trieRoot = new TrieNode(false);
fs.readFileSync(fileName, 'utf8')
.split(/\s+/)
.forEach((word) => this.insert(word.toLowerCase()));
}
insert(word) {
// Do not insert word if it is too long or short
if (word.length < 2 || word.length > 16) return;
let curr = this.trieRoot;
for (const char of word) {
// Create node if it doesn't exist
if (!curr.children[this._ord(char)])
curr.children[this._ord(char)] = new TrieNode(false);
curr = curr.children[this._ord(char)];
}
curr.valid = true;
}
contains(word) {
let curr = this.trieRoot;
for (const char of word) {
if (!curr.children[this._ord(char)]) return false;
curr = curr.children[this._ord(char)];
}
return curr.valid;
}
getRoot() {
return this.trieRoot;
}
getChild(node, char) {
return node?.children[this._ord(char)];
}
_ord(char) {
return char.charCodeAt(0) - 97;
}
}
class TrieNode {
constructor(valid) {
this.valid = valid;
this.children = new Array(26);
}
}
export default Dictionary;