简体   繁体   中英

How to shorten my conditional statements

I have a very long conditional statement like the following:

if(test.type == 'itema' || test.type == 'itemb' || test.type == 'itemc' || test.type == 'itemd'){
    // do something.
}

I was wondering if I could refactor this expression/statement into a more concise form.

Any idea on how to achieve this?

You can use switch statement with fall thru:

switch (test.type) {

  case "itema":
  case "itemb":
  case "itemc":
  case "itemd":
    // do something
}

Put your values into an array, and check if your item is in the array:

if ([1, 2, 3, 4].includes(test.type)) {
    // Do something
}

If a browser you support doesn't have the Array#includes method, you can use this polyfill .


Short explanation of the ~ tilde shortcut:

Update: Since we now have the includes method, there's no point in using the ~ hack anymore. Just keeping this here for people that are interested in knowing how it works and/or have encountered it in other's code.

Instead of checking if the result of indexOf is >= 0 , there is a nice little shortcut:

if ( ~[1, 2, 3, 4].indexOf(test.type) ) {
    // Do something
}

Here is the fiddle: http://jsfiddle.net/HYJvK/

How does this work? If an item is found in the array, indexOf returns its index. If the item was not found, it'll return -1 . Without getting into too much detail, the ~ is a bitwise NOT operator , which will return 0 only for -1 .

I like using the ~ shortcut, since it's more succinct than doing a comparison on the return value. I wish JavaScript would have an in_array function that returns a Boolean directly (similar to PHP), but that's just wishful thinking ( Update: it now does. It's called includes . See above). Note that jQuery's inArray , while sharing PHP's method signature, actually mimics the native indexOf functionality (which is useful in different cases, if the index is what you're truly after).

Important note: Using the tilde shortcut seems to be swathed in controversy, as some vehemently believe that the code is not clear enough and should be avoided at all costs (see the comments on this answer). If you share their sentiment, you should stick to the .indexOf(...) >= 0 solution.


A little longer explanation:

Integers in JavaScript are signed, which means that the left-most bit is reserved as the sign bit; a flag to indicate whether the number is positive or negative, with a 1 being negative.

Here are some sample positive numbers in 32-bit binary format:

1 :    00000000000000000000000000000001
2 :    00000000000000000000000000000010
3 :    00000000000000000000000000000011
15:    00000000000000000000000000001111

Now here are those same numbers, but negative:

-1 :   11111111111111111111111111111111
-2 :   11111111111111111111111111111110
-3 :   11111111111111111111111111111101
-15:   11111111111111111111111111110001

Why such weird combinations for the negative numbers? Simple. A negative number is simply the inverse of the positive number + 1; adding the negative number to the positive number should always yield 0 .

To understand this, let's do some simple binary arithmetic.

Here is how we would add -1 to +1 :

   00000000000000000000000000000001      +1
+  11111111111111111111111111111111      -1
-------------------------------------------
=  00000000000000000000000000000000       0

And here is how we would add -15 to +15 :

   00000000000000000000000000001111      +15
+  11111111111111111111111111110001      -15
--------------------------------------------
=  00000000000000000000000000000000        0

How do we get those results? By doing regular addition, the way we were taught in school: you start at the right-most column, and you add up all the rows. If the sum is greater than the greatest single-digit number (which in decimal is 9 , but in binary is 1 ) we carry the remainder over to the next column.

Now, as you'll notice, when adding a negative number to its positive number, the right-most column that is not all 0 s will always have two 1 s, which when added together will result in 2 . The binary representation of two being 10 , we carry the 1 to the next column, and put a 0 for the result in the first column. All other columns to the left have only one row with a 1 , so the 1 carried over from the previous column will again add up to 2 , which will then carry over... This process repeats itself till we get to the left-most column, where the 1 to be carried over has nowhere to go, so it overflows and gets lost, and we're left with 0 s all across.

This system is called 2's Complement . You can read more about this here:

2's Complement Representation for Signed Integers .


Now that the crash course in 2's complement is over, you'll notice that -1 is the only number whose binary representation is 1 's all across.

Using the ~ bitwise NOT operator, all the bits in a given number are inverted. The only way to get 0 back from inverting all the bits is if we started out with 1 's all across.

So, all this was a long-winded way of saying that ~n will only return 0 if n is -1 .

Using Science: you should do what idfah said and this for fastest speed while keep code short:

THIS IS FASTER THAN ~ Method

var x = test.type;
if (x == 'itema' ||
    x == 'itemb' ||
    x == 'itemc' ||
    x == 'itemd') {
    //do something
}

http://jsperf.com/if-statements-test-techsin 在此输入图像描述 (Top set: Chrome, bottom set: Firefox)

Conclusion :

If possibilities are few and you know that certain ones are more likely to occur than you get maximum performance out if || , switch fall through , and if(obj[keyval]) .

If possibilities are many , and anyone of them could be the most occurring one, in other words, you can't know that which one is most likely to occur than you get most performance out of object lookup if(obj[keyval]) and regex if that fits.

http://jsperf.com/if-statements-test-techsin/12

i'll update if something new comes up.

If you are comparing to strings and there is a pattern, consider using regular expressions.

Otherwise, I suspect attempting to shorten it will just obfuscate your code. Consider simply wrapping the lines to make it pretty.

if (test.type == 'itema' ||
    test.type == 'itemb' ||
    test.type == 'itemc' ||
    test.type == 'itemd') {
    do something.
}
var possibilities = {
  "itema": 1,
  "itemb": 1,
  "itemc": 1,
…};
if (test.type in possibilities) { … }

Using an object as an associative array is a pretty common thing, but since JavaScript doesn't have a native set you can use objects as cheap sets as well.

if( /^item[a-d]$/.test(test.type) ) { /* do something */ }

或者如果物品不均匀,那么:

if( /^(itema|itemb|itemc|itemd)$/.test(test.type) ) { /* do something */ }

Excellent answers, but you could make the code far more readable by wrapping one of them in a function.

This is complex if statement, when you (or someone else) read the code in a years time, you will be scanning through to find the section to understand what is happening. A statement with this level of business logic will cause you to stumble for a few seconds at while you work out what you are testing. Where as code like this, will allow you to continue scanning.

if(CheckIfBusinessRuleIsTrue())
{
    //Do Something
}

function CheckIfBusinessRuleIsTrue() 
{
    return (the best solution from previous posts here);
}

Name your function explicitly so it immediately obvious what you are testing and your code will be much easier to scan and understand.

You could put all the answers into a Javascript Set and then just call .contains() on the set.

You still have to declare all the contents, but the inline call will be shorter.

Something like:

var itemSet = new Set(["itema","itemb","itemc","itemd"]);
if( itemSet.contains( test.type ){}

One of my favorite ways of accomplishing this is with a library such as underscore.js...

var isItem = _.some(['itema','itemb','itemc','itemd'], function(item) {
    return test.type === item;
});

if(isItem) {
    // One of them was true
}

http://underscorejs.org/#some

another way or another awesome way i found is this...

if ('a' in oc(['a','b','c'])) { //dosomething }

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)  o[a[i]]='';
  return o;
}

of course as you can see this takes things one step further and make them easy follow logic.

http://snook.ca/archives/javascript/testing_for_a_v

using operators such as ~ && || ((),()) ~~ is fine only if your code breaks later on. You won't know where to start. So readability is BIG.

if you must you could make it shorter.

('a' in oc(['a','b','c'])) && statement;
('a' in oc(['a','b','c'])) && (statements,statements);
('a' in oc(['a','b','c']))?statement:elseStatement;
('a' in oc(['a','b','c']))?(statements,statements):(elseStatements,elseStatements);

and if you want to do inverse

('a' in oc(['a','b','c'])) || statement;

Just use a switch statement instead of if statement:

switch (test.type) {

  case "itema":case "itemb":case "itemc":case "itemd":
    // do your process
  case "other cases":...:
    // do other processes
  default:
    // do processes when test.type does not meet your predictions.
}

Switch also works faster than comparing lots of conditionals within an if

For very long lists of strings, this idea would save a few characters (not saying I'd recommend it in real life, but it should work).

Choose a character that you know won't occur in your test.type, use it as a delimiter, stick them all into one long string and search that:

if ("/itema/itemb/itemc/itemd/".indexOf("/"+test.type+"/")>=0) {
  // doSomething
}

If your strings happen to be further constrained, you could even omit the delimiters...

if ("itemaitembitemcitemd".indexOf(test.type)>=0) {
  // doSomething
}

...but you'd have to be careful of false positives in that case (eg "embite" would match in that version)

For readability create a function for the test (yes, a one line function):

function isTypeDefined(test) {
    return test.type == 'itema' ||
           test.type == 'itemb' ||
           test.type == 'itemc' ||
           test.type == 'itemd';
}

then call it:

…
    if (isTypeDefined(test)) {
…
}
...

I think there are 2 objectives when writing this kind of if condition.

  1. brevity
  2. readability

As such sometimes #1 might be the fastest, but I'll take #2 for easy maintenance later on. Depending on the scenario I will often opt for a variation of Walter's answer.

To start I have a globally available function as part of my existing library.

function isDefined(obj){
  return (typeof(obj) != 'undefined');
}

and then when I actually want to run an if condition similar to yours I'd create an object with a list of the valid values:

var validOptions = {
  "itema":1,
  "itemb":1,
  "itemc":1,
  "itemd":1
};
if(isDefined(validOptions[test.type])){
  //do something...
}

It isn't as quick as a switch/case statement and a bit more verbose than some of the other examples but I often get re-use of the object elsewhere in the code which can be quite handy.

Piggybacking on one of the jsperf samples made above I added this test and a variation to compare speeds. http://jsperf.com/if-statements-test-techsin/6 The most interesting thing I noted is that certain test combos in Firefox are much quicker than even Chrome.

This can be solved with a simple for loop:

test = {};
test.type = 'itema';

for(var i=['itema','itemb','itemc']; i[0]==test.type && [
    (function() {
        // do something
        console.log('matched!');
    })()
]; i.shift());

We use the first section of the for loop to initialize the arguments you wish to match, the second section to stop the for loop from running, and the third section to cause the loop to eventually exit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM