Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut to compare if statements [duplicate]

Tags:

javascript

if (Progress.bar.status == 'finished' || Progress.bar.status == 'uploading'){
  //code here
}

How do I shorten this? I'd like to write it without having to repeat Progress.bar.status twice.

Something along the lines of:

Progress.bar.status == ('finished' or 'uploading').
like image 285
Rich Avatar asked Jun 22 '15 07:06

Rich


3 Answers

I like lookup tables:

if ({finished:1, uploading:1}[Progress.bar.status]){
  //code here
}

this uses an object to code two or more options, and even side-steps quoting every choice. its also very fast since the object can be cached and there is no comparison logic or methods to invoke, just fast property access driving the flow...

do note that in some cases, you might want to use Object.create(null) and then merge/extend that blank object with your options, if you absolutely must avoid false-positives for "hasOwnProperty", "valueOf", "toString", "toLocaleString", "constructor", and a few double-underscore extensions. it's not often an issue, but it is something to keep in mind. if you can live without feeding your if those keywords, or building a cached collection of choices from Object.create(), it's a fast and simple way to code "one of the above" flows.

like image 141
dandavis Avatar answered Oct 24 '22 19:10

dandavis


I can suggest working with enumerations then a switch() statement:

var Status = {
    Finished: 'finished', 
    Uploading: 'uploading'
};

switch (Progress.bar.status) {
    case Status.Finished:
    case Status.Uploading:
      //code here
      break;
}

More code initially, but more flexible and readable.

like image 25
Shadow Wizard Hates Omicron Avatar answered Oct 24 '22 21:10

Shadow Wizard Hates Omicron


Make with the wanted strings an array, apply a search for the index of the array. The result is -1 for not found and 0 ... n for a found string. to make this short and while we need only the 0 ... n result, apply a bitwise not to the result (https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT) :

value  ~value   boolean
 -1  =>   0  =>  false
  0  =>  -1  =>  true
  1  =>  -2  =>  true
  2  =>  -3  =>  true
  and so on 

In code all together it looks like this:

if (~['finished', 'uploading'].indexOf(Progress.bar.status)) {
    // code here
}
like image 29
Nina Scholz Avatar answered Oct 24 '22 20:10

Nina Scholz