Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient Javascript Array Lookup

If I have a whitelist of strings that I want to check everything the user inputs into my javascript program, what's the most efficient way to do that? I could just have an array and loop through it until a match has been found but that's O(N). Is there an yway to do it that's better and doesn't involve any sort of key value lookup, just checking to see if that value exists?

EDIT: I guess what I'm looking for is the equivalent of a set in C++ where I can just check to see if a value I'm given already exists in the set.

like image 829
barndog Avatar asked Oct 22 '22 14:10

barndog


1 Answers

Just make it a simple js object instead of an array.

var whitelist = {
  "string1":true,
  "string2":true
}

and then you can just check if(whitelist[str]) to check if its available.

Or use if(str in whitelist).

I expect that the first will have slightly better performance (I haven't verified that), but the second is more readable and makes the purpose clear. So its your choice of which is a better fit.

like image 96
Ben McCormick Avatar answered Oct 27 '22 11:10

Ben McCormick