Trie Prefix Search And Autocomplete (JavaScript)
Build a trie from a word list supporting prefix search and autocomplete suggestions ranked by word frequency.
Code
class TrieNode {
constructor() { this.children = {}; this.isWord = false; this.freq = 0; }
}
class Trie {
constructor() { this.root = new TrieNode(); }
insert(word, freq = 1) {
let node = this.root;
for (const ch of word) {
if (!node.children[ch]) node.children[ch] = new TrieNode();
node = node.children[ch];
}
node.isWord = true; node.freq += freq;
}
suggest(prefix, limit = 5) {
let node = this.root;
for (const ch of prefix) { node = node.children[ch]; if (!node) return []; }
const results = [];
const dfs = (n, path) => {
if (n.isWord) results.push({ word: path, freq: n.freq });
for (const [ch, child] of Object.entries(n.children)) dfs(child, path + ch);
};
dfs(node, prefix);
return results.sort((a, b) => b.freq - a.freq).slice(0, limit).map(r => r.word);
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.