2
我正在構建一個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;
}
}
看起來像這可能是一個很好的實現我使用:http://stackoverflow.com/a/5023187/324085 – thedjpetersen 2012-01-31 21:09:53
你知道是否有任何其他常見的JavaScript實現的Trie? – thedjpetersen 2012-01-31 22:38:58
@ thedjpetersen-我不是一個JavaScript編碼器,所以我不知道標準的實現。也就是說,如果不存在一個好的特里實施,我會非常驚訝。 – templatetypedef 2012-01-31 23:31:32