【问题标题】:How to refactor my autocomplete application如何重构我的自动完成应用程序
【发布时间】:2017-10-13 23:25:43
【问题描述】:

我编写了一个示例自动完成应用程序,可以按我的预期工作。

HTML

<div class="wrapper">
    <div class="search">
        <input type="text" id="search" placeholder="Search" onkeyup="autoComplete(this.value)">
        <button onclick="search()">Go</button>
        <ul id="suggest">

        </ul>
    </div>
    <div class="result">

    </div>
</div>

脚本

var data = ['Bob', 'Aria', 'Smith', 'Jack', 'Cethy', 'Brad', 'Jony', 'Dan', 'Ashley', 'Janice'];
    var suggestionArray = [];
    var search = function(){
        var searchTerm  = document.getElementById('search').value;
        if(searchTerm == undefined || searchTerm == ""){
            return false;
        }
        console.log('You are searching for ' + searchTerm);
    }

    var clearSuggestion = function() {
        suggestionArray = [];
    }

    var addListenersToChild = function(){
        var el = document.getElementById('suggest');
        el.addEventListener('click', function(event){
            var searchTerm = event.target.textContent;
            document.getElementById('search').value = searchTerm;
            clearSuggestion();
            showSuggestion();
        }, false)
    }

    var showSuggestion = function(){
        var el = document.getElementById('suggest');
        el.innerHTML = "";
        if(suggestionArray.length>0){
            suggestionArray.forEach(function(suggestTerm){
                var node = document.createElement('li');
                var textnode = document.createTextNode(suggestTerm);
                node.appendChild(textnode);
                el.appendChild(node);
            });
            addListenersToChild();
        }
    }

    var formSuggestionArray = function(dataTerm){
        if(suggestionArray.indexOf(dataTerm) > -1){
            return false;
        } else {
            suggestionArray.push(dataTerm);
        }
    }

    var matchVal = function(val){
        clearSuggestion();
        for(var i=0; i<data.length;i++){
            if(data[i].toLowerCase().indexOf(val.toLowerCase()) > -1) {
                formSuggestionArray(data[i]);
            }
        }
    }

    var autoComplete = function(val){
        if(val == undefined || val == ""){
            clearSuggestion();
            showSuggestion();
            return false;
        }
        matchVal(val);
        showSuggestion();
    }

我不确定我编写代码的方式是否是最好的方式。因此,例如,我需要知道的是,如果我当前的程序是

  • 利于可读性
  • 已优化
  • 是否遵循最佳做法

如何改进代码

【问题讨论】:

    标签: javascript refactoring code-readability


    【解决方案1】:

    在我看来很棒,但是...

    var data = ['Bob', 'Aria', 'Smith', 'Jack', 'Cethy', 'Brad', 'Jony', 'Dan', 'Ashley', 'Janice'];
    var suggestionArray = [];
    /* Caching these two element nodes speeds things up a bit.. */
    var search_element = document.getElementById('search');
    var suggestion_element = document.getElementById('suggest');
    
    var search = function(){
        var searchTerm  = search_element.value;
        // concise falsey, TRUE IF `searchTerm` == 0 || undefined || ""
        if(!searchTerm){
            return false;
        }
        console.log('You are searching for ' + searchTerm);
    }
    
    /* 
        plurize because contains multiple values,
        optionally can just do `suggestionArray.length = 0` equivalent
    */
    var clearSuggestions = function() {
        suggestionArray = [];
    }
    
    var addListenersToChild = function(){
        suggestion_element.addEventListener('click', function(event){
            var searchTerm = event.target.textContent;
            search_element.value = searchTerm;
            clearSuggestions();
            showSuggestion();
        }, false)
    }
    
    var showSuggestion = function(){
        suggestion_element.innerHTML = "";
        /* implicit casting/coersion - IF length == 0 (false) ELSE (true) */
        if(suggestionArray.length){
            /* reuse this `node` variable */
            var node;
            suggestionArray.forEach(function(suggestTerm){
                node = document.createElement('li');
                node.textContent = suggestTerm;
                /*
                    too verbose/unnecessary in my opinion
    
                var textnode = document.createTextNode(suggestTerm);
                node.appendChild(textnode);
                */
                suggestion_element.appendChild(node);
            });
            addListenersToChild();
        }
    }
    
    
    var formSuggestionArray = function(dataTerm){
        /* you can use a native `Set` for `suggestionArray`, insures unique entries */
    
        if(suggestionArray.indexOf(dataTerm) > -1){
            return false;
        } else {
            suggestionArray.push(dataTerm);
        }
    }
    
    var matchVal = function(val){
        clearSuggestions();
        for(var i=0; i<data.length;i++){
            if(data[i].toLowerCase().indexOf(val.toLowerCase()) > -1) {
                formSuggestionArray(data[i]);
            }
        }
    }
    
    var autoComplete = function(val){
        // concise falsey, TRUE IF `val` == 0 || undefined || ""
        if(!val){
            clearSuggestions();
            showSuggestion();
            return false;
        }
        matchVal(val);
        showSuggestion();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多