Trie Prefix Search And Autocomplete Typed

Build a typed trie from a word list supporting prefix search and autocomplete suggestions ranked by frequency.

TypescriptData Fetching

Code

typescriptsnippet
20 lines
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);
  }
}

How it works

Trie Prefix Search And Autocomplete Typed is built around the classes TrieNode and Trie and the function dfs.

The structure is a loop within a loop: for (const ch of word) { let next = node.children.get(ch); if (!next) { next = new TrieNode(); no… outside, for (const ch of prefix) { node = node.children.get(ch)!; if (!node) return []; } inside.

The return value is newly constructed — inputs are never handed back.

Watch out for

  • The guard !node short-circuits the flow with an early return when its condition holds.

Applying it

The entry-point signature is const dfs = (n: TrieNode, path: string)

Statements that matter

return results.sort((a, b) => b.freq - a.freq).slice(0, limit).map(r => r.word);
for (const ch of prefix) { node = node.children.get(ch)!; if (!node) return []; }
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);
};

Interactive Tools for This Topic

FAQ

Does `dfs` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `dfs` at load time.