OneCompiler

Trie in JS

187

function Node(){
this.isword = false;
this.children = [];
for(var i = 0; i < 26; i++)
{
this.children.push(null);
}
this.check_isword = function(){
return this.isword;
};
this.on_isword = function(){
this.isword = true;
};
this.set_child = function(index){
if(index < 26 && this.children[index] == null){
this.children[index] = new Node();
}
};
}

let root = new Node();

function Trie(){
this.root = new Node();

this.get_index = function(ch){
return ch.charCodeAt(0) - "a".charCodeAt(0);
};

this.insert = function(word){
var curr_root = this.root;
for(var i = 0; i < word.length; i++)
{
curr_root.set_child(this.get_index(word[i]));
curr_root = curr_root.children[this.get_index(word[i])];
}
curr_root.on_isword();
};

this.search = function(word){
var curr_root = this.root;
for(var i = 0; i < word.length; i++)
{
if(curr_root.children[this.get_index(word[i])] !== null)
curr_root = curr_root.children[this.get_index(word[i])];
else return false;
}
return curr_root.check_isword();
};

this.suggest = function(word){
var curr_root = this.root;
for(var i = 0; i < word.length; i++)
{
if(curr_root.children[this.get_index(word[i])])
curr_root = curr_root.children[this.get_index(word[i])];
else break;
}
if(curr_root.check_isword() === true)
return [word];
else
{
return['suggest','some','words'];
}
};
};

const v = new Trie();
v.insert("hello");
v.insert("he");
;
console.log(v.suggest("hl"));