ChatGPT解决这个技术问题 Extra ChatGPT

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 put them in an array and use in?
now only if someone could check which one is the fastest
this maybe a shock to everyone but what OP has is a clear winner in speed!!!!!!! Maybe cause browser optimize for this a lot.. Results: (1) if with ||. (2) switch statements. (3) regex. (4) ~. jsperf.com/if-statements-test-techsin
You may also be approaching this the wrong way. In this case, those 4 types have something in common. What is it? If we take this to a more extreme case, what if we needed to add 10 more types to match this condition. Or 100? If there were more, you probably wouldn't consider using this solution, or any of the others suggested. You're seeing a big if statement like this, and thinking it's a code smell, which is a good sign. Your best way to make this more concise would be if you could write if (test.your_common_condition). It's easier to understand in this context, and more extensible.

J
Joseph Silber

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 0s will always have two 1s, 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 0s 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.


Whilst using bitwise operators sure is sexy, is it really better than !== -1 in any conceivable way? Isn't explicit boolean logic more appropriate than implicitly using the falsey-ness of zero?
Nicely techy, but I don't like it. It's not clear at first glance what the code is doing, which makes it unmaintainable. I much prefer "Yuriy Galanter"'s answer.
-1 new programmers see answers like this, think it's a cool and acceptable way of coding, then in 5 years I have to maintain their code and tear my hair out
This idiom is definitely not common in languages like C#, Java, or Python, which are my areas of expertise. And I just asked a few of the local Javascript experts here, and none of them have ever seen it done before; so it is clearly not as common as you claim. It should always be avoided in favor of the much clearer and more common != -1.
-1 due to unnecessary bitfiddling in a language which doesn't really specify a lot about bit representations in the first place. Plus, the bulk of this answer is explaining the bitfiddling. If you have to write 20 paragraphs to explain the hack, does it REALLY save any time?
Y
Yuriy Galanter

You can use switch statement with fall thru:

switch (test.type) {

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

its basically the same as the if, the index of array method is far far better
@kojiro its sadly, the right answer is this, but its impossible to get attention to this instead of the awesome bitwhise-array trick.
I knew this answer had to be here but I had to scroll way down to the bottom to find it. It's exactly what the switch statement was designed for and carries over to many other languages. I have found a lot of people don't know about the 'fall through' method in a switch statement.
This solution is the fastest one on Firefox and Safari and second fastest (after the original ||) on Chrome. See jsperf.com/if-statements-test-techsin
I think this would be awful to write in a method if you had many conditions... It if fine for a few conditions, but for more than 10 I would go for the array to keep code neat.
M
Muhammad Umer

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
}

https://i.stack.imgur.com/Y69mv.jpg

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.


+1 for a really good post! If I understand correctly, the switch case is the fastest method?
in firefox yes, in chrome its if ( ...||...||...)...
It's faster if you really do many loops over this input, but it's much slower if you have one loop with very large n (number of "itemX" strings). I hacked up this code generator that you can use to verify (or perhaps refute). obj["itemX"] is extremely fast if n is large. Basically, what's fast depends on context. Have fun.
So it's the fastest method, but does it matter?
@Mich Don't sacrifice elegance of code just for speed. This is what many many people will say to you. In the end, just use common sense.
i
idfah

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.
}

this answer is the winner in terms of speed jsperf.com/if-statements-test-techsin
This is also the easiest to expand when the project goes into maintenance mode (with rules such as, (test.type == 'itemf' && foo.mode == 'detailed'))
k
kojiro
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.


How is this shorter than the normal if statement that FlyingCat is trying to shorten?
@dcarson OP's if statement's conditional takes 78 characters if you remove all whitespace. Mine takes 54 if you write it like this: test.type in {"itema":1,"itemb":1,"itemc":1,"itemd":1}. Fundamentally, his uses four characters for every two mine use for each additional key.
but you can do: if(possibilities[test.type]) and save a whole 2 chars! :)
M
Matt
if( /^item[a-d]$/.test(test.type) ) { /* do something */ }

or if the items are not that uniform, then:

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

"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." - Jamie Zawinski, 1997
@MosheKatz While I can understand people like to bandy about that quote - and people certainly do use regular expressions for wholly unsuitable things, but this is not one of them. In the case provided by the OP, this not only matches the criteria, it does so very well. Regular expressions are not inherently evil, and matching strings with well defined parameters is what it's made for.
@Thor84no Usually, I would assume that the questioner is not actually attempting to match against such a contrived example as the first case, and that the real-world matches are not so simple, in which case I don't think a RegEx is going to be the right way to do it. To put it another way, if your RegEx is just a pipe-character separated list of options, it's not any more readable than any of the other suggestions, and possibly significantly less efficient.
F
Fran Hoey

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.


Best answer I have seen here. Really, I see that people do not care about principles of good design. Just want to fix something quickly and forget to improve the code so that the system be maintainable in the future!
How about just commenting like // CheckIfBusinessRuleIsTrue?
G
Guido Anselmi

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 ){}

That seems like an incredibly wasteful way to accomplish what the OP is trying to do. So while you could include an extra 3rd-party library, instantiate an object, and the call a method on it, you probably shouldn't.
@Captain Cold: Well the OP asked for conciseness not memory footprint. Maybe the set could be reused for other operations?
Sure, but even so: Would you in all honesty ever do this yourself? If I ever saw this in the wild, I would consider it a major WTF.
Yeah you are right (I gave you the +1s) but it assumes that this check is being done nowhere else. If it is being done in several other places and/or the test changes, then the use of the Set might make sense. I leave it to the OP to choose the best solution. All that said if this was a solitary usage I would agree that using the Set would deserve the A-s Clown hat of shame.
I actually think the chosen answer is absolutely awful and worse then using the Set as it is absolutely unreadable.
j
jcreamer898

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


contains is arguably a better solution than some
No need to use a library for this: some is a function on the Array prototype in EC5.
True, but not everyone has EC5 support available. Plus, I just really like underscore. :)
If you are already using a library like underscore, this is probably the easiest way. Otherwise, it makes little sense to load a whole library just for the one function.
M
Muhammad Umer

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;

u
unmultimedio

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


C
CupawnTae

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 (e.g. "embite" would match in that version)


z
zaph

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)) {
…
}
...

s
scunliffe

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

brevity 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.