I was looking for better autocomplete alghoritm and i found out about trie. I have implemented basic trie
var trie = {};
for( var i = 0 ; i < words.length ; i++){
var tmp_word = words[i];
var tmp_arr = tmp_word.split("");
var current = trie;
for( var j = 0; j < tmp_arr.length; j++){
var letter = tmp_arr[j];
var pos = current [ letter ];
if( pos == null ){
current [ letter ] = j === tmp_arr.length - 1 ? 0 : {};
current =current [ letter ];
}
else if ( pos === 0 ) {
current [ letter ] = { $: 0 };
current =current [ letter ]
}
else{
current = current [ letter ];
}
}
}
which will take words from array and create key from every letter. For example if array is
var words = [ "Hello" , "world" ,"Helis" ]
it will create this
{
"H": {
"e": {
"l": {
"l": {
"o": 0
},
"i": {
"o": {
"s": 0
}
}
}
}
},
"w": {
"o": {
"r": {
"l": {
"d": 0
}
}
}
}
}
What i am struggling with is find a word to complete. E.g if i input "He" it should return Hello and Helios , what is best way how to do it? The only thing that come into my mind is brute force loop which would be really ineffective and slow. Is there any more effective way than brute force?