Trie Prefix Search And Autocomplete Typed
Build a typed trie from a word list supporting prefix search and autocomplete suggestions ranked by frequency.
Code
class TrieNode { children: Map<string, TrieNode> = new Map(); isWord = false; freq = 0; }
class Trie {
root = new TrieNode();
insert(word: string, freq = 1): void {
let node = this.root;
for (const ch of word) { let next = node.children.get(ch); if (!next) { next = new TrieNode(); node.children.set(ch, next); } node = next; }
node.isWord = true; node.freq += freq;
}
suggest(prefix: string, limit = 5): string[] {
let node = this.root;
for (const ch of prefix) { node = node.children.get(ch)!; if (!node) return []; }
const results: { word: string; freq: number }[] = [];
const dfs = (n: TrieNode, path: string): void => {
if (n.isWord) results.push({ word: path, freq: n.freq });
for (const [ch, child] of 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.