【问题标题】:Tab completion from array of strings字符串数组的制表符补全
【发布时间】:2012-02-01 05:01:27
【问题描述】:

我正在构建一个 IRC 客户端,我希望实现一个选项卡完整名称的解决方案。我有一个数组形式的用户列表。当用户按下制表键时,它会完成用户名。当他们再次按下该键时,下一个用户就完成了。

我在这里有一个可行的解决方案,但我觉得它可以更加优化和简洁一些。如有任何建议,我将不胜感激。

// Get Active Window
var channel = irc.chatWindows.getActive();
// Get users input
var sentence = $('#chat-input').val().split(' ');
// Get the last word in the sentence
var partialMatch = sentence.pop();
// Get list of users
var users = channel.userList.getUsers();
// Set default index for loop
var userIndex=0;
//Persist the match
//Store the partialMatch to persist next time the user hits tab
if(window.partialMatch === undefined) {
  window.partialMatch = partialMatch;
} else if(partialMatch.search(window.partialMatch) !== 0){
  window.partialMatch = partialMatch;
} else {
  if (sentence.length === 0) {
    userIndex = users.indexOf(partialMatch.substr(0, partialMatch.length-1));
  } else {
    userIndex = users.indexOf(partialMatch);
  }
}
//Cycle through userlist from last user or beginning
for (var i=userIndex; i<users.length; i++) {
  var user = users[i] || '';
  //Search for match
  if (window.partialMatch.length > 0 && user.search(window.partialMatch, "i") === 0) {
    //If no match found we continue searching
    if(user === partialMatch || user === partialMatch.substr(0, partialMatch.length-1)){
      continue;
    }
    //If we find a match we return our match to our input
    sentence.push(user);
    //We decide whether or not to add colon
    if (sentence.length === 1) {
      $('#chat-input').val(sentence.join(' ') +  ":");
    } else {
      $('#chat-input').val(sentence.join(' '));
    }
    //We break from our loop
    break;
  }
}

【问题讨论】:

    标签: javascript string optimization data-structures autocomplete


    【解决方案1】:

    您可能需要查看 trie 数据结构,该结构非常适合此问题。使用 trie,您可以非常有效地列出所有以给定前缀开头的字符串,而无需查看单词列表中的所有单词。您还可以使用 trie 进行其他不错的操作,例如快速查找、快速后继和前驱搜索以及快速插入/删除。

    希望这会有所帮助!

    【讨论】:

    • 看起来这对我来说可能是一个很好的实现:stackoverflow.com/a/5023187/324085
    • 你知道javascript中是否还有其他常见的Trie实现?
    • @thedjpetersen- 我不是 JavaScript 编码员,所以我不知道标准实现。也就是说,如果不存在好的 trie 实现,我会感到非常惊讶。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    • 1970-01-01
    相关资源
    最近更新 更多