javascript - 字符串数组中的制表符补全

标签 javascript string optimization data-structures autocomplete

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

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

// 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;
  }
}

最佳答案

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

希望这有帮助!

关于javascript - 字符串数组中的制表符补全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9086862/

相关文章:

javascript - 为什么我的 Jquery Modals 会通过模态上的任何按钮关闭?

javascript - 服务 worker 返回的 javascript 响应对象中的 json 内容

regex - Python 3如何使用正则表达式在两点之间获取字符串?

php - 如何在另一个字符串中插入一个字符串?

c++ - RVO, move 语义和优化代码的斗争

javascript - 为多个&lt;input&gt;添加随机id

c# - 如何从字符串创建名称为对象的对象?

java - 在java代码中频繁提交插入数据库是一个好习惯吗?

c++ - 使用 oracle occi 和 c++ 将 1300 万行转储到文件中

javascript - 将位图从 Flash 电影传输到 Javascript