search-faster
Version:
nvm package for search functionality using trie
55 lines (49 loc) • 1.32 kB
JavaScript
class TrieNode {
constructor() {
this.children = {};
this.isEndOfWord = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let currentNode = this.root;
for (const char of word) {
if (!currentNode.children[char]) {
currentNode.children[char] = new TrieNode();
}
currentNode = currentNode.children[char];
}
currentNode.isEndOfWord = true;
}
searchPrefix(prefix) {
let currentNode = this.root;
for (const char of prefix) {
if (!currentNode.children[char]) {
return null;
}
currentNode = currentNode.children[char];
}
return currentNode;
}
suggest(prefix) {
const node = this.searchPrefix(prefix);
if (!node) {
return [];
}
const suggestions = [];
this._findAllWords(node, prefix, suggestions);
return suggestions;
}
_findAllWords(node, prefix, suggestions) {
if (node.isEndOfWord) {
suggestions.push(prefix);
}
for (const char in node.children) {
this._findAllWords(node.children[char], prefix + char, suggestions);
}
}
}
module.exports = Trie