我正在构建一个 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/