Reputation: 33571
I have conditionals like this:
if (foo == 'fgfg' || foo == 'asdf' || foo == 'adsfasdf') {
// do stuff
}
Surely there's a faster way to write this?
Thanks.
Upvotes: 5
Views: 383
Reputation: 1
Use tilde (~) for a shorter expression
if (~["fgfg", "asdf", "adsfasdf"].indexOf(foo)) {
//do stuff
}
Upvotes: 0
Reputation: 3446
Here's a easy way:
String.prototype.testList = function(lst) {
lst = lst.split('|');
for(var i=0; i<lst.length; i++){
if (this == lst[i]) return true;
}
return false;
};
To use this function, you can just do this:
if (foo.testList('fgfg|asdf|adsfasdf')) {
You can also rename testList
to whatever you want, and change the delimiter from |
to anything you want.
Upvotes: 1
Reputation: 6833
I would keep the conditionals the way they are. Any clever way of shortening them would make the code less idiomatic and less readable.
Now, if you do care about readability, you could define a function to do the comparison:
if( foo_satisfies_condition(foo) ) {
// ...
}
Or:
if( is_month_name(foo) {
// ...
}
If you give the function a name that faithfully describes what it does, it will be easier to understand the intent of the code.
How you implement that function would depend on how many comparisons you need. If you have a really large number of strings you're comparing against, you could use a hash. The implementation details are irrelevant when reading the calling code, though.
Upvotes: 4
Reputation: 66978
No need for using indexOf
or a regex if you just use a hash table:
var things = { 'fgfg' : 1, 'asdf' : 1, 'asdfasdf' : 1 };
if ( things[foo] ) {
...
}
Upvotes: 4
Reputation: 284836
if (/^(fgfg|asdf|adsfasdf)$/.test(foo)) {
or:
if (["fgfg", "asdf", "adsfasdf"].indexOf(foo) != -1) {
Cross-browser support for Array.indexOf
is still limited. Also, these are faster to write, probably not faster to run.
Upvotes: 4
Reputation: 45667
You might consider a switch-case statement
switch(foo) {
case "fgfg":
case "asdf":
case "adsfasdf":
// ...
}
It's not really any shorter, but could be more readable depending on how many conditions you use.
Upvotes: 6
Reputation: 12397
Depending on the situation you could do..
//At some point in your code var vals = new Array('fgfg', 'asdf', 'adsfasdf'); //... if(vals.indexOf(foo) >= 0)
Upvotes: 0