views:

55

answers:

3

This code is to be integrated into an AJAX Chat system to enable a tab auto-completion of user names:

var usernames = new Array();
usernames[0] = "Saladin";
usernames[1] = "Jyllaby";
usernames[2] = "CadaverKindler";
usernames[3] = "qbsuperstar03";

var text = "Text and something else q";

// Start of the script to be imported
var searchTerm = text.slice(text.lastIndexOf(" ") + 1);
var i;
for(i = 0; i < usernames.length && usernames[i].substr(0,searchTerm.length) != searchTerm; i++);
// End of the script to be imported

document.write(usernames[i]);

A couple of notes to be made: The array of usernames and the text variable would both be loaded from the chat itself via AJAX (which, unfortunately, I don't know), and the final output will be handled by AJAX as well.

Is there a more efficient way to do this?

Also, any tips on how to handle multiple instances of the searchTerm being found?

A: 

You can make this significantly more efficient (provided large number of users) by keeping the array sorted and using binary search to find the match.

Fyodor Soikin
A: 

The way you have it coded now:

for(i = 0; i < usernames.length && usernames[i].substr(0,searchTerm.length) != searchTerm; i++);

You are checking the length of usernames and the length of searchTerm as well as getting a substr from usernames[i] EVERY time the loop uh, loops.

For any of these that you don't expect to change during the course of the loop, you should store them in a variable before the loop starts.

Getting a value out of a variable is much faster than checking an object property or method.

So something like:

for(i = 0,ii=usernames.length,j=searchTerm.length; i < ii && usernames[i].substr(0,j) != searchTerm; i++);
MisterMister
A: 

Micro-optimization: instead of getting the substring and comparing it (creating lots of temporary strings)...

usernames[i].substr(0,searchTerm.length) != searchTerm

...you should use indexOf, which creates no temporary strings...

usernames[i].indexOf(searchTerm) == 0

What do you mean by "multiple instances of the searchTerm being found"? Can you give an example of the problem you're thinking of?

Chris Schmich
If the searchTerm is, for example, 'var' and there are two usernames starting with 'var' - Varsity and Variety, let's say... In the chat situation, you may want the second result, but at the moment it only picks the first it finds.
Saladin Akara
Use a JavaScript array and add each matching user to it. If the user wants to see all matching results, you have them all already. If you want to just show the first or last result, then you can get it from the array through indexing.See http://www.hunlock.com/blogs/Mastering_Javascript_Arrays for details.
Chris Schmich