Trie Prefix Search And Autocomplete (JavaScript)

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

JavascriptData Fetching

Code

javascriptsnippet
25 lines
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);
  }
}

What the code does

Count the classes TrieNode and Trie and the function dfs as the entire surface area of Trie Prefix Search And Autocomplete (JavaScript).

The nesting pairs for (const ch of word) with for (const ch of prefix) { node = node.children[ch]; if (!node) return []; } — the inner runs once per outer step.

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

Points of care

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

Applying it

Entry signature: const dfs = (n, path)

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[ch]; if (!node) return []; }
node.isWord = true; node.freq += freq;

Interactive Tools for This Topic

FAQ

Does `dfs` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `dfs` at load time.