2

I am building an IRC client and I am hoping to implement a solution to tab complete names. I have a list of users in the form of an array. When the user presses the tab key it completes the username. When they press the key again it completes with the next user.

I have a working solution here, but I feel like it could be a little more optimized and terse. I would be grateful for any suggestions.

// 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;
  }
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
thedjpetersen
  • 27,857
  • 4
  • 26
  • 28

1 Answers1

3

You may want to look into the trie data structure, which is excellently structured for exactly this problem. With a trie, you can list off all of the strings that start with a given prefix very efficiently and without having to look at all the words in the word list. You can also do other nice operations with the trie, such as fast lookups, fast successor and predecessor search, and fast insertion/deletion.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065