Skip to content

Instantly share code, notes, and snippets.

@JustAyush
Created April 4, 2020 04:17
Show Gist options
  • Save JustAyush/43f6d255d78c267478c8cdd9bff2bd33 to your computer and use it in GitHub Desktop.
Save JustAyush/43f6d255d78c267478c8cdd9bff2bd33 to your computer and use it in GitHub Desktop.
Trie Implementation in Javascript
class TrieNode {
constructor(key) {
this.key = key;
this.parent = null;
this.children = {};
this.end = false;
}
// for finding out word from leaf to root of trie
findWord() {
let node = this;
let word = [];
while(node.parent != null) {
word.unshift(node.key);
node = node.parent;
}
return word.join('');
}
}
class Trie {
constructor(){
this.root = new TrieNode(null);
}
// to insert the word letter by letter in the trie
insert(word) {
let node = this.root;
for(let i=0; i<word.length; i++) {
if(!node.children[word[i]]) {
node.children[word[i]] = new TrieNode(word[i]);
node.children[word[i]].parent = node;
}
node = node.children[word[i]];
if(i == word.length - 1)
node.end = true;
}
}
// check to see if the trie contains the word or not
containsWord(word) {
let node = this.root;
for(let i=0; i<word.length; i++) {
if(!node.children[word[i]]) return false;
node = node.children[word[i]];
}
return node.end;
}
// gives the autocomplete suggestion for given prefix in form of an array
autocomplete(prefix) {
let node = this.root;
let output = [];
for(let i=0; i<prefix.length; i++) {
if(!node.children[prefix[i]]) return output;
node = node.children[prefix[i]];
}
this.findAllWords(node, output);
return output;
}
// recursively find all the words by exploring all of its children nodes
findAllWords(node, output) {
if(node.end) {
output.push(node.findWord());
} else {
for(var i in node.children) {
this.findAllWords(node.children[i], output)
}
}
}
// check to see there is word(s) starting with the given prefix
startsWith(prefix) {
let node = this.root;
for(let i=0; i<prefix.length; i++) {
if(!node.children[prefix[i]]) return false;
node = node.children[prefix[i]];
}
return true;
}
print() {
console.log(this.root);
}
}
let t = new Trie();
t.insert('apple');
t.insert('ant');
t.insert('andromedia')
console.log(t.containsWord('ant')); // output: true
console.log(t.containsWord('banana')); // output: false
console.log(t.autocomplete('an')); // output: ['ant', 'andromedia']
console.log(t.autocomplete('b')); // output: []
console.log(t.startsWith('and')); // output: true
t.print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment