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').
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With