-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrie.js
88 lines (71 loc) · 2 KB
/
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
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
class Trie {
constructor(letter=null, terminating=false) {
this.letter = letter;
this.terminating = terminating;
this.children = {};
}
fill(...words) {
words.forEach(word => this.addWord(word));
}
addWord(word) {
if(!word) return word;
if(this.letter === word[0]) this.addLetters(word.substr(1));
this.addLetters(word);
return this;
}
isValid(word) {
const letters = word.split('');
let current = this;
while(letters.length > 0) {
const char = letters.shift();
if(current.children[char]) {
current = current.children[char];
} else {
return false;
}
}
return current.terminating;
}
read(prefix) {
const letters = prefix.split('');
let current = this;
while(letters.length > 0) {
const letter = letters.shift();
if(current.children[letter]) {
current = current.children[letter];
} else {
return null;
}
}
return Array.from(this.words(current)).map(each => `${prefix.slice(0, -1)}${each}`);
}
words(currentNode = this) {
const wordsFound = new Set();
const depthFirstSearch = (node, letters=[]) => {
const lettersFound = [].concat(letters);
if(node.letter) {
lettersFound.push(node.letter);
if(node.terminating) {
wordsFound.add(lettersFound.join(''));
}
}
for(let child in node.children) {
depthFirstSearch(node.children[child], lettersFound);
}
};
depthFirstSearch(currentNode);
return wordsFound;
}
addLetters(word) {
if(word.length < 1) return word;
const firstLetter = word[0];
const remaining = word.substr(1);
const terminating = word.length === 1;
if(this.children[firstLetter]) {
this.children[firstLetter].addLetters(remaining);
} else {
this.children[firstLetter] = new Trie(firstLetter, terminating);
this.children[firstLetter].addLetters(remaining);
}
}
}