class Trie {
constructor(words) {
this.root = new TrieNode();
if (words) {
words.forEach(w => this.insert(w))
}
}
insert(word) {
let node = this.root;
for (const char of word) {
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.isEndOfWord = true;
}
search(prefix) {
let node = this.root;
for (const char of prefix) {
if (node.children[char]) {
node = node.children[char];
} else {
return []
}
}
return this._getWords(node, prefix)
}
getOptions() {
return this._getWords(this.root, "")
}
_getWords(node, prefix) {
let words = [];
if (node.isEndOfWord) {
words.push(prefix);
}
for (const [key, childNode] of Object.entries(node.children)) {
words.push(...this._getWords(childNode, prefix + key))
}
return words
}
}