Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Created October 5, 2023 04:03
Show Gist options
  • Select an option

  • Save carefree-ladka/57bfe9b0cac3cfbd61b8a5e06cc73f48 to your computer and use it in GitHub Desktop.

Select an option

Save carefree-ladka/57bfe9b0cac3cfbd61b8a5e06cc73f48 to your computer and use it in GitHub Desktop.
Trie Implementation in JavaScript . It also includes Auto-complete.
class TrieNode {
constructor() {
this.children = {};
this.end = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert = (word) => {
let node = this.root;
for (let i = 0; i < word.length; i++) {
const char = word[i];
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.end = true;
};
/**
* Auto-complete feature.
* @tutorial O(P) where P is the prefix length
*/
search = (word) => {
let node = this.root;
for (const char of word) {
if (!node.children[char]) return [];
node = node.children[char];
}
return this.findWords(node, word);
};
findWords = (node, prefix) => {
const suggestions = [];
if (node.end) suggestions.push(prefix);
for (const char in node.children) {
suggestions.push(...this.findWords(node.children[char], prefix + char));
}
return suggestions;
};
startsWith = (prefix) => {
let node = this.root;
for (let i = 0; i < prefix.length; i++) {
const char = prefix[i];
if (!node.children[char]) return false;
node = node.children[char];
}
return true;
};
delete = (word) => {
this.#deleteRecursively(this.root, word, 0);
};
#deleteRecursively = (node, word, index) => {
const hasDeleted = Object.keys(node.children).length === 0;
if (index === word.length) {
if (node.end) node.end = false;
return hasDeleted;
}
const char = word[index];
if (!node.children[char]) return false; //Word doesnt exist
const shouldDeleteChild = this.#deleteRecursively(
node.children[char],
word,
index + 1
);
if (shouldDeleteChild) {
delete node.children[char];
return hasDeleted;
}
return false;
};
}
const trie = new Trie();
trie.insert("apple");
trie.insert("appetizer");
trie.insert("banana");
trie.insert("bat");
trie.insert("ball");
trie.delete("banana");
console.log(trie.startsWith("ba")); //true
console.log(trie.search("ba")); //[ 'bat', 'ball' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment