I recently got interviewed in a company for Senior level position. They asked me to develop auto-complete component (2 hours time limit) using plain JavaScript similar to this.
I wrote below code, which works as expected, but they responded saying that the solution doesn't match expectations. Please help me figure out what I could improve in this.
Here is the link to working example.
function customAutoComplete(input,sourceList){
if(!input){
console.error('No input box provided');
}
if(!sourceList || sourceList.length<=0){
console.error('No sourceList provided for customAutoComplete');
}
var suggList;
input.addEventListener('keyup',function(e){
suggList=populateSourceList(input.value);
if(suggList){
input.parentNode.appendChild(suggList);
}
if(e.keyCode==40){
suggList.focus();
}
});
input.addEventListener('blur',function(e){
if(e.relatedTarget.id!=input.id + '_autoComplete'){
setTimeout(clearSuggestionList,200);
}
});
function populateSourceList(inputText){
if(!inputText){
return null;
}
var suggList=getSuggestList();
var size=1;
sourceList.forEach( function(itm){
if(itm.indexOf(inputText)>=0) {
var listItem=document.createElement("option");
listItem.appendChild(document.createTextNode(itm));
suggList.appendChild(listItem);
size++;
}
});
suggList.setAttribute('size',size);
if(size>1){
return suggList;
}
return null;
}
function getSuggestList(){
var acListId=input.id + '_autoComplete';
var acList= document.getElementById(acListId)
if(!acList){
acList = document.createElement("select");
acList.setAttribute('class','suggestion-list');
acList.setAttribute('id',acListId);
var stl='left:' + input.offsetLeft + 'px;top:' + (input.offsetTop + input.offsetHeight) + 'px;min-width:' + input.offsetWidth + 'px';
acList.setAttribute('style',stl);
acList.addEventListener('keydown',function(e){autoCompleteItemSelected(e,acList)});
acList.addEventListener('blur', function(){clearSuggestionList(suggList)} );
}
else{
acList.innerHTML='';
}
return acList;
}
function clearSuggestionList(suggList){
if(!suggList){
suggList=getSuggestList();
}
suggList.outerHTML='';
}
function autoCompleteItemSelected(e,list){
if(e.keyCode==13){
input.value=list.selectedOptions[0].text;
clearSuggestionList();
}
}
}